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

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

How to select specific column after relationship in where condition?

1

There are 1 best solutions below

1
N69S On BEST ANSWER

You can condition the relation using with()

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

If you want only the Warehouse_other_receive_detail that have product_sub_group->sub_group_id = 2 use 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();