Home > Software design >  using 'where' in the pivot table
using 'where' in the pivot table

Time:09-27

I have a portal_user table and portal_roles table. I have a pivot table pivot_user_roles which connects users to their roles.

    class Role extends Model
{
    use HasFactory;
    protected $table = 'portal_roles';
    
    protected $hidden = array('created_at', 'updated_at','deleted_at');
    
    public function users()
    {
    return $this->belongsToMany(User::class, 'portal_user_roles');
    }
}

class UserRole extends Model
{
    use HasFactory;
    protected $table = 'portal_user_roles';
    
    protected $fillable = ['user_id','role_id'];
    
     
}

I am using the following code to search for the users which belongs to a particular role

$resultset = '';
$searchquery = $data['query'];

    $rolesobj = Role::find($type_id);
    if (self::checksearchtype($searchquery) == NAME_ONEPART) {
            
      

        $resultset = $rolesobj->users->where('firstname', 'like', '%' . $searchquery . '%');
  

The above

where

statement is not yielding any results. I am expecting that the above statement will search in the users table to find the user depending on the role selected and the name (or part of the name) passed.

CodePudding user response:

$rolesobj->users()->where(...)->get()

You need to call users relation to do it. Because mutators directly fetch items from database when you try to access it as a property.

btw, also you can add some conditions in your case.

$rolesobj->users->where(...

But in this case, you have a collection object, and you can't query it as you tried

  • Related