If I have a table called users
:
| id | username | password |
And a table called user_stats
:
| id | user_id | num_posts |
How can I get all users and sort them by the number of posts they have?
My User.php
model has this relationship:
public function stats()
{
return $this->hasOne('App\UserStat');
}
And my UserStat.php
model has this relationship:
public function user()
{
return $this->belongsTo('App\User');
}
I know I can do a join using the query builder, like:
$users = User::join('user_stats', 'users.id', '=', user_stats.user_id')
->orderBy('user_stats.num_posts', 'DESC')
->get();
But is there a better way to do it using just the Eloquent ORM?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire