簡體   English   中英

Laravel 5.4-既選擇又選擇加載子孫

[英]Laravel 5.4 - Eager Loading Child and Grandchild with Select Both

我試圖通過兩個后代選擇加載兩個深厚的關系(子代和孫代)。 但是,當我向孫子項添加addSelect()方法時,它將返回一個空數組。 我有以下內容:

$products = Category::with([
   'products' => function($q){ $q->addSelect(['product_name', 'product_desc']);},
   'products.productgroup' => function($q){ $q->addSelect(['price']);}
])->where('id', 1)->get();

這將返回類別和產品約束,但產品組將作為一個空數組返回。

如果我運行以下命令:

$products = Category::with('products', 'products.productgroup')->where('id', 1)->get();

我得到了包括產品組數據在內的所有數據的預期回報。 僅當我將addSelect()方法添加到products或products.productgroup時,它才返回一個空數組。 我在這里想念什么嗎?

我在堆棧或laravel論壇上找不到任何類似的問題,我很困惑。

編輯: 包括來自調試欄的查詢

調試欄中出現的查詢是:

30.55ms
select * from `categories` where `id` = '1'
29.38ms
homestead
select `product_name`, `category_product`.`category_id` as`pivot_category_id`, `category_product`.`product_id` as `pivot_product_id` from `products` inner join `category_product` on `products`.`id` = `category_product`.`product_id` where `category_product`.`category_id` in ('1')
730μs
homestead
select `price` from `product_groups` where `product_groups`.`product_id` in ('')

我不是100%忙於查詢加載器的工作原理。 當在產品查詢或產品組查詢上存在addSelect()時,似乎產品ID沒有傳遞到product_groups查詢。

好的,答案很簡單。 當使用addSelect()從子代和孫代中選擇列時,我沒有選擇product.idproductgroup.product_id 為了將孫子代映射到子節點,顯然需要product.idproductgroup.product_id 它應該是:

$products = Category::with(['products' => function($q){
    $q->with(['productgroups' => function($g){
        $g->addSelect(['id', 'price', 'product_id']);
    }])->addSelect(['id', 'product_name', 'product_desc']);
}])->where('id', 1)->get();

希望這對遇到急切負載的孫節點的其他人返回空數組有所幫助。

HT到埃迪鴿子

我使用了他的嵌套格式,該格式重現了同樣的問題,但是在語法上比我自己的方法更簡潔。

這樣嘗試

$products = Category::with(['products' => function($q){ 
    $q->with(['productgroup' => function($a) {
        $a->addSelect(['price']);
    }])->addSelect(['product_name', 'product_desc']);
})->where('id', 1)->get();

如果可以,請嘗試以下方法:

$product_ids = Category::find(1)->products()->pluck('id');
$prices = ProductGroup::whereIn('product_id', $product_ids)->pluck('price');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM