2

How i can use where clause in many to many relation ship

Table: Users

   id - name - email

Table: Shiftings

   id - name

Table: shifting_user

   id - user_id - shifting_id

User Model:

public function shiftings()
{
    return $this->belongsToMany('App\shifting');
}

in controller im using below custom query

public function index()
{
    return $user = DB::select('select * from shifting_user
    where user_id in (select id from users)' );
}

how i can convert this to laravel standard/equloent query.

1 Answers1

0

You need to setup their relationships first.

In your Shifting model:

public function users()
{
    return $this->belongsToMany(User::class);
}

In your User model:

public function shiftings ()
{
     return $this->belongsToMany(Shifting::class);
}

Then you can get all shiftings including it's users associated with by simply doing an eager loading

$shiftings = Shifting::with('users')->get();
dd($shiftings);
Dexter Bengil
  • 5,995
  • 6
  • 35
  • 54