Try changing property.prices to property_prices.price :)
Jun 22, 2017
7
Level 7
Filter By Relationship value and sort It
I have this tables
properties
-id
-name
property_prices
-id
-property_id
-date
-price
Property.php
public function currentPrice()
{
return $this->hasOne(PropertyPrice::class)
->orderBy('date', 'DESC')
->where('date', '<=', Carbon::now());
}
PropertyPrice.php
public function property() {
return $this->belongsTo(Property::class);
}
// My Request Data
// sortby = 'asc' or 'dsc'
// min = 100
// max = 1000
SearchController.php
public function index(Request $request) {
$query = Property::query();
// get the price for the before today or today.
$query->whereHas('currentPrice', function ($q) {
$q->whereBetween('price', [10, 50000]);
});
if ($request->sortby) {
$query->orderBy('property.prices', $request->sortby);
}
return $query->paginate(15);
}
I'm getting an error of column property.prices does not exist.
I made it work using Raw Query but I need to convert it to eloquent so I can use and orderBy method.
$query = DB::select(DB::raw(
"SELECT
initial_property_price.*, properties.*
FROM property_prices as initial_property_price
INNER JOIN
(SELECT
property_prices.property_id, max(property_prices.date) as max_date
FROM property_prices
WHERE property_prices.date <= now()
GROUP BY property_prices.property_id) as original_property_price
on initial_property_price.property_id = original_property_price.property_id
AND initial_property_price.date = original_property_price.max_date
INNER JOIN properties
on initial_property_price.property_id = properties.id
WHERE properties.status = 'Active'"
));
Level 22
@Eco012390 just add ORDER BY property_prices.price at the end of your query. Check out this link for more info and examples: https://www.w3schools.com/sql/sql_orderby.asp
As for the duplicating properties, you can be explicit what you want to select using the select() method.
Please or to participate in this conversation.