$data = Model\Recipe::with(['ingredient', 'tags'])->find($recipeId);
if (empty($data)) {
return ResponseData::set($data);
}
$data->getInfoImage()->getListImage()->getPrice($locale);
return ResponseData::set($data);
上面一段程式碼,出現了13次的資料庫查詢。雖然說在本機每次查詢速度很快,但是扛不住查詢數量多。
基本資料如下:
{
"SQL":"select * from `ak_recipe` where `ak_recipe`.`id` = ? and `ak_recipe`.`deleted_at` is null limit 1",
"bindings":[
"148"
],
"time":0.00037
},
{
"SQL":"select * from `ak_recipe_image` where `type` = ? and `recipe_id` = ? and `ak_recipe_image`.`deleted_at` is null limit 1",
"bindings":[
2,
148
],
"time":0.00046
},
{
"SQL":"select * from `ak_recipe_image` where `type` = ? and `recipe_id` = ? and `ak_recipe_image`.`deleted_at` is null limit 1",
"bindings":[
1,
148
],
"time":0.00035
},
// 。。。。
如果說,資料庫從本機切換到內網,那麼每個SQL的執行資料基本上是翻倍的。
資料如下:
{
"SQL":"select * from `ak_recipe` where `ak_recipe`.`id` = ? and `ak_recipe`.`deleted_at` is null limit 1",
"bindings":[
"148"
],
"time":0.00073
},
{
"SQL":"select * from `ak_recipe_image` where `type` = ? and `recipe_id` = ? and `ak_recipe_image`.`deleted_at` is null limit 1",
"bindings":[
2,
148
],
"time":0.00075
},
{
"SQL":"select * from `ak_recipe_image` where `type` = ? and `recipe_id` = ? and `ak_recipe_image`.`deleted_at` is null limit 1",
"bindings":[
1,
148
],
"time":0.00077
},
// 。。。。
不知道大家是如何處理這種關聯關係查詢的?是自己寫JOIN
去查詢碼?還是說有其他方式去結局這個問題。
大家讲道理2017-05-16 16:54:17
應該沒必要寫原生SQL吧,改造下$data->getInfoImage()->getListImage()->getPrice($locale);
我看文檔,有關聯關係指定預加載查詢的額外條件是類似這樣的:
$users = App\User::with(['posts' => function ($query) {
$query->where('title', 'like', '%first%');
}])->get();
文檔連結