Reputation: 12923
I have a scoped method on a laravel model:
public function scopeSort($query, array $params = []) {
return $query->orderBy('read');
}
What I would like to do is say: if there are no items with read = true, then orderByDesc on id.
For example:
public function scopeSort($query, array $params = []) {
return $query->orderBy('read')->orOrderByDesc('id');
// Find all with a read of true or, if there is none, order the collection by id in descending order.
}
Does anything like this exist? Or is there some other way I can achieve this?
Upvotes: 0
Views: 19089
Reputation: 1
public function scopeSort($query, array $params = []) {
return $query->orderBy('read')->orderBy('created_at','desc')
// or you can try with id as well
}
Upvotes: 0
Reputation: 1041
You can chain your sorts :
public function scopeSort($query, array $params = []) {
return $query->orderBy('read')->orderBy('id','desc');
}
Example with :
ID read
1 0
4 0
3 0
You'll get :
ID read
4 0
3 0
1 0
Example with :
ID read
1 0
4 1
3 1
5 0
6 1
You'll get :
ID read
5 0
1 0
6 1
4 1
3 1
In the case where all read = 0, the query will sort by ID desc. In the case where there are some read = 1, the query will sort by read, then ID.
EDIT: to be precise, the query will always sort by 'read' then 'ID', but I guess you'll have what you want
Upvotes: 1