lumen - laravel 关联关系查询,会出现大量查询如何解决?
为情所困
为情所困 2017-05-16 16:52:17
0
3
467
        $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去查询码?还是说有其他方式去结局这个问题。

为情所困
为情所困

全部回复(3)
左手右手慢动作

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

大家讲道理

应该没必要写原生SQL吧,改造下$data->getInfoImage()->getListImage()->getPrice($locale);我看文档,有关联关系指定预加载查询的额外条件是类似这样的:

$users = App\User::with(['posts' => function ($query) {
    $query->where('title', 'like', '%first%');

}])->get();

文档链接

Peter_Zhu

用DB门面代替Eloquent ORM。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板