[英]Laravel Eloquent hasMany filtered by parent table
在我的系统中,有一些用户,每个用户每年都有假期津贴。
有3个表(简化):
使用者
- ID
- 名称
user_leave_allowances
- ID
- 用户身份
-来自
- 至
-津贴
user_leave
- ID
- 用户身份
-来自
- 至
- 天
在UserLeaveAllowance模型中,我建立了以下关系:
public function leave(){
return $this->hasMany('App\UserLeave','user_id','user_id');
}
并通过以下方式获取假期津贴:
$leaveAllowance = UserLeaveAllowance::with(['leave'])
->where('user_id',$id)
->get()
这将获取该用户的休假津贴(user_leave_allowances)的完整列表以及他们当前已请求的所有休假(user_leave)。
但是,津贴将针对不同的时间段,例如1/1/2017-31/12/2017,并将在这些时间段内休假。 因此,对于每个休假津贴期,我只希望属于这两个日期(从&到)内的休假,此刻,它只是将该用户的所有休假纳入每个休假津贴。
我已经尝试了许多不同的方法,例如使用hasMany的where条件。
public function used(){
return $this->hasMany('App\UserLeave','user_id','user_id')
->where('from', '>=', 'user_leave_allowances.from')
->where('to', '<=', 'user_leave_allowances.to');
}
和
public function used(){
return $this->hasMany('App\UserLeave','user_id','user_id')
->whereRaw('user_leave.from >= user_leave_allowances.from')
->whereRaw('user_leave.to <= user_leave_allowances.to');
}
但是我只是想不出一种方法来使它工作。 我对Laravel并不陌生,想与Eloqent和人际关系保持紧密联系,我相信答案不会太遥远。
这是我的建议:
用户 -ID-名称
user_leave_allowances -id- user_id-从-到
user_leave -id-user_leave_allowances_id-从-到
简而言之,请假与您的请假津贴而不是与使用者直接联系,因为从本质上说,请假是从津贴中提取的,而不是直接从使用者中提出的。
class User extends Model {
public leaveAllowance() {
return $this->hasMany(UserLeaveAllowance::class);
}
}
class UserLeaveAllowance {
public user() { return $this->belongsTo(User::class); }
public leaveRequests() {
return $this->hasMany(UserLeave::class);
}
}
class UserLeave {
public allowancePeriod() {
return $this->belongsTo(UserLeaveAllowance::class);
}
}
现在您可以执行以下操作:
UserLeaveAllowance::whereHas("user", function ($q) {
return $q->where("id", <user id>); //Allowances for this user
})->leaveRequests()
->selectRaw("SUM(TIMESTAMPDIFF(DAY, to, from)) as days")
->value("days");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.