简体   繁体   中英

Searching from multiple related table using laravel 5 Eager Loading

Actually i have 4 related model and searching data from two table using criteria. Using following query i get result if i ignore searching from address model. But i need search from both Property and Address model in which show error for address table column.

        $min_price  = !empty($request['min_price']) ? $request['min_price'] : 500;
        $max_price  = !empty($request['max_price']) ? $request['max_price'] : 50000000000;
        $arrCriteria = [
                'properties.status'            => 1,
                'properties.category'          => $request['search_category'],
                'properties.type'              => $request['contract'],
                'addresses.city'               => $request['search_city'], //show error
                'addresses.area'               => $request['property_area'],  //show error
                'properties.bed_room'          => $request['search_bedroom'],
                'properties.bath_room'         => $request['bath_room'],
        ];
        $property = Property::with('address', 'photo', 'user')
                        ->where($arrCriteria)
                        ->whereBetween('properties.price', [$min_price, $max_price])
                        ->get();

the error you have encounter, is due to your property table has no addresses.city & addresses.area columns, in order to filter & eager loading your relation at the same time, you have to write something as below

$arrCriteria = [ 'properties.status' => 1, 'properties.category' => $request['search_category'], 'properties.type' => $request['contract'], 'properties.bed_room' => $request['search_bedroom'], 'properties.bath_room' => $request['bath_room'], ];

$addressCriteria = [
'addresses.city' => $request['search_city'],
'addresses.area' => $request['property_area'],
];

and finally

$property = Property::with(['address' => function ($query) use ($addressCriteria) {
    return $query->where($addressCriteria);
}, 'photo', 'user'])
    ->where($arrCriteria)
    ->whereBetween('properties.price', [$min_price, $max_price])
    ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM