简体   繁体   English

使用laravel 5从多个相关表中搜索渴望加载

[英]Searching from multiple related table using laravel 5 Eager Loading

Actually i have 4 related model and searching data from two table using criteria. 实际上,我有4个相关模型,并使用条件从两个表中搜索数据。 Using following query i get result if i ignore searching from address model. 如果我忽略从address模型搜索,则使用以下查询可以获得结果。 But i need search from both Property and Address model in which show error for address table column. 但是我需要从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();

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 您遇到的错误,是由于您的属性表没有addresss.city和addresss.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'],
];

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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