英文:
Laravel has relationship query on another table
问题
我有一个用户模型和一个日程模型。我试图在Laravel中使用关联而不是进行联接操作。是否可以返回所有具有班次的用户,其中班次时间 = 'x'?我想要返回所有具有特定日期范围内班次的用户。
$users = User::select('name','location','id AS user_id')->has('shift')->whereHas('shift', function ($query) use ($start) {
$query->where('startTime', $start);
})->get();
这段代码应该可以实现你的需求。
英文:
I have a user model and a Schedule model. I am trying to use relationships in Laravel instead of doing a join. Is it possible to return all users that have shifts where shift time = 'x' ? I would like to return all users that have shifts between a specific date range.
$users = User::select('name','location','id AS user_id')->has('shift')>where('schedule.startTime', $start)->get();
This obviously doesn't work because the start column exists in the Schedule Model.
In my User Model I have:
public function shift() {
return $this->hasMany('App\Models\Schedule');
}
In my Schedule Model I have:
public function user()
{
return $this->belongsTo('App\Models\User', 'user_id', 'id');
}
In my Schedule Controller I am using the below which works but I need to narrow down by my results by a where clause:
$users = User::select('name','location','id AS user_id')->has('shift')->get();
Any help is appreciated.
答案1
得分: 2
看一下 eager loading
类似下面的代码应该可以解决问题。
User::whereHas('schedule', function ($query) {
return $query->where('startTime', $start);
})->get();
英文:
Take a look at
eager loading
Something like the following should do the trick.
User::whereHas('schedule', function ($query) {
return $query->where('startTime', $start);
})->get();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论