I got a many to many user and role structure
users
id
name
roles
id
name
role_user
user_id
role_id
Model
User.php
public function roles() {
return $this->belongsToMany('Role');
}
Role.php
public function users() {
return $this->belongsToMany('User');
}
There are two data admins
and members
in roles table, I would like to know to to filter users which role is admins.
A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.
all() is a static method on the Eloquent\Model. All it does is create a new query object and call get() on it. With all(), you cannot modify the query performed at all (except you can choose the columns to select by passing them as parameters). get() is a method on the Eloquent\Builder object.
Eager loading is super simple using Laravel and basically prevents you from encountering the N+1 problem with your data. This problem is caused by making N+1 queries to the database, where N is the number of items being fetched from the database.
This should give you all users who are admins.
$users = User::whereHas('roles', function($q) {
$q->where('name', '=', 'admins');
})->get();
You can see more information on the has()
method at http://laravel.com/docs/eloquent#querying-relations
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With