slverstone
slverstone

Reputation: 115

orderBy on whereHas query in Laravel 4.2

how can I sort the return data from a query using whereHas? In my query i have to get the users data which id exist on interest table but i need to sort it using the datetime column from interest. But, the return query do not sort the data at all.

Here's my code snippets in case it would help you understand my problem.

Model (name: User)

//***relationship***//
public function interest(){
     return $this->belongsTo('Interest','id','interest_by');
}

Controller

$userInterested = User::whereHas('interest',function($q) use ($id) {
     return $q->where('interest_on', $id)
              ->orderBy('datetime');
});
$userQuery = $userInterested->get();
return $userQuery;

Upvotes: 6

Views: 2383

Answers (2)

lucidlogic
lucidlogic

Reputation: 1944

$userInterested = User::whereHas('interest',function($q) use ($id) {
     return $q->where('interest_on', $id);
})->orderBy('datetime');
$userQuery = $userInterested->get();
return $userQuery;

Upvotes: 0

Imtiaz Pabel
Imtiaz Pabel

Reputation: 5443

remove return from where has and try this.like

$userInterested = User::whereHas('interest',function($q) use ($id) {
  $q->where('interest_on', $id)
          ->orderBy('datetime');
 })->get();
 return $userInterested;

Upvotes: 1

Related Questions