使用laravel 5 Eager Loading从多个相关表中搜索

时间:2015-04-11 18:03:38

标签: php laravel laravel-4 eloquent laravel-5

实际上我有4个相关模型,并使用标准从两个表中搜索数据。如果我忽略从address模型的搜索,使用以下查询我得到结果。但我需要从PropertyAddress模型中搜索,其中显示地址表列的错误。

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

1 个答案:

答案 0 :(得分:0)

您遇到的错误,是由于您的属性表没有address.city& addresses.area列,以便过滤&渴望加载你的关系,你必须写下面的东西

$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'],
];

最后

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