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

Searching from multiple related table using laravel 5 Eager Loading

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

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

您遇到的错误是由于您的 属性 table 没有 addresses.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();