lumen - laravel relationship query, there will be a large number of queries, how to solve it?
为情所困
为情所困 2017-05-16 16:52:17
0
3
475
        $data = Model\Recipe::with(['ingredient', 'tags'])->find($recipeId);

        if (empty($data)) {
            return ResponseData::set($data);
        }

        $data->getInfoImage()->getListImage()->getPrice($locale);
        return ResponseData::set($data);

The above code contains 13 database queries. Although each query on this machine is very fast, it cannot handle the large number of queries.

Basic data are as follows:

{
    "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
},
// 。。。。

If the database is switched from the local machine to the intranet, then the execution data of each SQL will basically double.

Data are as follows:

{
    "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
},
// 。。。。

I don’t know how everyone handles this kind of relationship query? Should I write JOIN myself to query the code? Or is there another way to resolve this issue?

为情所困
为情所困

reply all(3)
左手右手慢动作

ORM efficiency is relatively slow. If you are looking for the best performance, you might as well try using the DB class directly

大家讲道理

There shouldn’t be any need to write native SQL. After modification$data->getInfoImage()->getListImage()->getPrice($locale);I looked at the documentation and found that the additional conditions for specifying preloaded queries in relation are similar to this:

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

}])->get();

Documentation link

Peter_Zhu

Replace Eloquent ORM with DB facade.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template