[英]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.