lumen - laravel 關聯關係查詢,會出現大量查詢如何解決?
为情所困
为情所困 2017-05-16 16:52:17
0
3
484
        $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。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板