搜尋

首頁  >  問答  >  主體

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去查詢碼?還是說有其他方式去結局這個問題。

为情所困为情所困2741 天前464

全部回覆(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
  • 取消回覆