php - speed up query laravel [solve] -
i need help. in db have 2 tables
my db have 2 table's contracts (around 2 500 000 records) , customers (around 1 500 000 records). relationship between 2 tables/2 models.
class contract extends model { public function customer() { return $this->belongsto('app\customer'); } } class customer extends model { public function contracts() { return $this->hasmany('app\contract'); } } with community stack built function
$customers = customer::with(['contracts' => function($query) { $query->where('pos', 'ropczyce') ->where('typ', 'u') ->where('data_end','>=','2017-07-01') ->where('data_end','<=','2017-08-31'); } ])->wherehas('contracts', function ($query) { $query->where('pos', 'ropczyce') ->where('typ', 'u') ->where('data_end','>=','2017-07-01') ->where('data_end','<=','2017-08-31'); }) ->paginate(20); but generate data spent lot of time (around 6-7 sec). imagine in moment, function working on customers , searching contracts query true. in opinion problem of the.
i searching solution save time. searching contracts spent around 1 seconds.
$contracts = contract::where('pos', 'ropczyce') ->where('typ', 'u') ->where('data_end','>=','2017-07-01') ->where('data_end','<=','2017-08-31') ->with('customer')->paginate(20); i care data built on principle. client1 - contact1, contract2 ... client2 - contact1, contract2 ...
e.t.c
code of table contract
public function up() { schema::create('contracts', function (blueprint $table) { $table->increments('id'); $table->integer('customer_id')->unsigned(); $table->char('phone_number',9); $table->date('data_start'); $table->date('data_end'); $table->char('contract_number',90); $table->char('pos',10); $table->char('typ',1); $table->char('weryfikacja',1); $table->date('data_weryfikacji'); }); }
you should add a composite index database these filters, make query faster.
schema::create('contracts', function (blueprint $table) { $table->increments('id'); $table->integer('customer_id')->unsigned(); $table->char('phone_number',9); $table->date('data_start'); $table->date('data_end'); $table->char('contract_number',90); $table->char('pos',10); $table->char('typ',1); $table->char('weryfikacja',1); $table->date('data_weryfikacji'); // composite index faster filtering on these fields. $table->index(['pos', 'typ', 'date_end']); });
Comments
Post a Comment