Laravel 在另一张表上有关联查询。

huangapple go评论59阅读模式
英文:

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();

huangapple
  • 本文由 发表于 2023年6月9日 09:41:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76436680.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定