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去查询码?还是说有其他方式去结局这个问题。

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 2

我也发现了这个问题,请问解决了吗

5年前 评论

可以使用匹配的原则,数据量少差别不大,但是数据量多了,就你能够看到差距

file

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!