搜索

首页  >  问答  >  正文

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

为情所困为情所困2804 天前517

全部回复(3)我来回复

  • ringa_lee

    ringa_lee2017-05-16 16:54:17

    ORM 效率是比较慢的,如果最求性能不妨试试直接使用DB类

    回复
    0
  • 大家讲道理

    大家讲道理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();
    

    文档链接

    回复
    0
  • 天蓬老师

    天蓬老师2017-05-16 16:54:17

    用DB门面代替Eloquent ORM。

    回复
    0
  • 取消回复