[英]Eager loading the first item from multiple value from a related table in laravel 5.4
[英]Searching from multiple related table using laravel 5 Eager Loading
实际上,我有4个相关模型,并使用条件从两个表中搜索数据。 如果我忽略从address
模型搜索,则使用以下查询可以获得结果。 但是我需要从Property
和Address
模型中搜索,其中地址表列显示错误。
$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();
您遇到的错误,是由于您的属性表没有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'],
];
最后
$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.