I've got table structure like this:
users:
- id
- name
managers:
- id
- user_id
user_manager:
- manager_id
- user_id
vacations:
- user_id
- date_from...
My task is to fetch all data from vacations table where user (vacations.user_id) belongs to given manager id (managers.user_id) and that assigment is in pivot table user_manager. User can have many managers, manager can have many users. I've been trying to do this, but I've got stuck. My workaround was this:
DB::table("vacations")
->leftJoin("users", function ($join) {
$join->on("vacations.user_id", "=", "users.id");
})
->leftJoin("user_manager", function ($join) {
$join->on("user_manager.user_id", "=", "users.id");
})
->where("user_manager.manager_id", "=", $id)
->get();
But I want to know a way to make this with eloquent model and all of it's fancy stuff.
Manager model:
class Manager extends Model
{
use HasFactory;
protected $table = 'managers';
protected $fillable = ['user_id'];
public function users()
{
return $this->belongsToMany(User::class, 'employee_manager')->withTimestamps();
}
}
User model:
class User extends Model
{
use HasFactory, Notifiable;
public function managers()
{
return $this->belongsToMany(Manager::class, 'employee_manager')->withTimestamps();
}
}
User
model's class name alsoManager
? And to make it clear; you are trying to fetch an exact manager's users who has a vacation plan, did I understand it right? – Uğur Arıcı