[英]Laravel Eloquent Relationship — How to Combine two Relationships on id and date?
[英]Laravel eloquent how to get relationships relationship?
我有用戶表、工作表和 JobStatus 表。 我使用關系獲得用戶工作
return User::find($dto->getUserId())
->jobs()
這會將所有用戶作業作為集合返回,而不是作為用戶 model 內部的關系返回。 現在我需要獲取工作狀態,但是當我嘗試這個時
User::find($dto->getUserId())
->jobs()
->statuses()
我收到錯誤Call to undefined method
。 我需要將狀態作為集合獲取,以便在從 db 獲取它們時使用 where、sort by 等。 有什么辦法嗎?
我需要做這樣的事情,但有狀態
return User::find($dto->getUserId())
->jobs()
->has('status')
->where('role','responsible')
->where('jobs.created_at','>=',Carbon::now()->subDays($dto->getPeriod())->toDateString())
->get();
要通過過濾狀態關系來檢索作業,您可以這樣做:
$user->jobs()->whereHas('statuses', function ($query) {
// Perform filter on the query for jobs->statuses
})->get();
有關查詢關系存在的更多信息: https://laravel.com/docs/7.x/eloquent-relationships#querying-relationship-existence
如果要檢索狀態實例,可以這樣做:
$statuses = JobStatus::where('created_at', '>=', now())
->whereHas('jobs', function ($query) use ($user) {
$query->whereUserId($user->id);
})
->get();
只需使用不帶括號的作業來獲取 model 本身:
User::find($dto->getUserId())
->jobs
->statuses;
首先使用 model 中的關系定義您的 statuses() function 與作業
喜歡多對多或一對多的關系
public function statuses(){
return $this->belongsToMany('App\Job')->withTimestamps();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.