Laravel 在主要关系的 where 条件中嵌套预加载特定列

Laravel nested eager loading specific columns in where condition in main relationship

$wo = Warehouse_other_receive_detail::with('item_info.product_sub_group')
    ->where('item_info.product_sub_group->sub_group_id', 2)
    ->get();

如何select where 条件下关系后的特定列?

您可以使用 with()

条件关系
$wo = Warehouse_other_receive_detail::with(['item_info.product_sub_group' => function($productSubGroup) {
        $productSubGroup->where('sub_group_id', '=', 2);
    }])
    ->get();

如果您只想要有 product_sub_group->sub_group_id = 2Warehouse_other_receive_detail,请使用 having()

$wo = Warehouse_other_receive_detail::having('item_info.product_sub_group', function($productSubGroup) {
        $productSubGroup->where('sub_group_id', '=', 2);
    })
    ->with(['item_info.product_sub_group' => function($productSubGroup) {
        $productSubGroup->where('sub_group_id', '=', 2);
    }])
    ->get();