S
S
Stanislav Pochepko2015-11-26 13:12:27
Laravel
Stanislav Pochepko, 2015-11-26 13:12:27

How to sort by one-to-many relationship?

How to sort by relationship?
The product has prices. The current price is selected based on the last one added. The price is stored as a separate Price object.

Product{
    public function prices(){
        return $this->hasMany(Price::class);
    }

    public function price(){
        return $this->prices()->orderBy('created_at', 'desc')->first();
    }
}

How to sort products by price? Sorting by selection result is not appropriate. It is necessary in the request.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Natarov, 2015-11-26
@HanDroid

In Laravel, you can sort by several parameters.

User::orderBy('name', 'DESC')
    ->orderBy('email', 'ASC')
    ->get();

the request itself is formed in this way.
Or join the goods by Id and sort them already by the general table.

V
Vyacheslav Plisko, 2015-11-26
@AmdY

$price = Price::orderBy('created_at', 'desc')->first();
$products = $price->products;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question