Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jericopulvera's avatar

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'"
        ));
0 likes
7 replies
andonovn's avatar

Try changing property.prices to property_prices.price :)

1 like
jericopulvera's avatar
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'property_prices.price' in 'order clause' (SQL: select * from `properties` where `status` = active and exists (select * from `property_prices` where `properties`.`id` = `property_prices`.`property_id` and `price` between 10 and 50000 and `date` <= 2017-06-23 01:19:13) and `properties`.`deleted_at` is null order by `property_prices`.`price` asc limit 1)

@andonovn I get this error

1 like
Christofer's avatar

The problem is that Select * From properties does not have that field (property_prices.price) in the list. You need to join porperty_prices to the main query to have access to that field.

PS: suggest using IN instead of EXISTS, much cleaner to select only one field in subquery and match it to one field in the main query. https://dev.mysql.com/doc/refman/5.7/en/any-in-some-subqueries.html

1 like
andonovn's avatar

Several approaches here:

  1. Use collect($query) to get a collection instance so you can use methods like orderBy()

  2. You can add an ORDER BY clause to your database query. In most cases it's faster than using php.

  3. If you really need to use the query builder, then check out this solution of nested selects - https://stackoverflow.com/questions/24823915/how-to-select-from-subquery-using-laravel-query-builder Join's usage is covered in the documentation - https://laravel.com/docs/5.4/queries#joins

jericopulvera's avatar

@andonovn how do I add an order by clause to my database query? is it an sql specific function?

I've been trying to do join all day but I'm not getting the result I wanted. the properties are duplicating in my collection.

Please or to participate in this conversation.