laraveleloquenteager-loadingeager

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();

How to select specific column after relationship in where condition?


Solution

  • 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();