Laravel 关联关系查询,会出现大量查询如何解决?
$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
去查询码?还是说有其他方式去结局这个问题。
推荐文章: