2017-02-20 141 views
6

我在laravel以下型號:查詢許多一對多在Laravel關係,同時限制關係存在

TheJobs 
- id 
- description 
- created_at 
- deleted_at 
- updated_at 

TheSeries 
- id 
- title 
- description 
- created_at 
- deleted_at 
- updated_at 


TheMovies 
- id 
- title 
- description 
- created_at 
- deleted_at 
- updated_at 


mSeriesJobs 
- seriesID 
- jobID 

mMoviesJobs 
- movieID 
- jobID 

這裏有關係的TheJobs

public function TheSeries() { 
    return $this->belongsToMany('App\Models\TheSeries', 'mSeriesJobs', 'jobID', 'seriesID'); 
    } 

    public function TheMovies() { 
    return $this->belongsToMany('App\Models\TheMovies', 'mMoviesJobs', 'jobID', 'movieID'); 
    } 

這裏有關係TheSeries

public function TheJobs() { 
    return $this->belongsToMany('App\Models\TheJobs', 'mSeriesJobs', 'seriesID', 'jobID'); 
    } 

同爲電影。

我想:

  • 得到所有TheSeries工作。
  • 獲得所有TheMovies工作。
  • 使用TheSeriesTheMovies數據獲取所有作業。

要澄清一個問題:

我需要一個簡單的雄辯查詢這將選擇至少有一個TheJobs所有TheSeries

+0

你能張貼的關係方法也? – xhulio

+0

@xhulio剛剛更新了 – Coder

+0

你還可以解釋一下你想要檢索的內容嗎?我的意思是,當你說'TheSeries'作業時,你的意思是隻有系列作品集或操縱的作品集,這些作品應該返回滿足 – xhulio

回答

0

在工作模式:

public function series() 
{ 
    return $this->hasMany('App\Series'); 
} 

系列型號:

public function jobs() 
{ 
    return $this->belongsToMany('App\Job'); 
} 

得到所有TheSeries工作:

$series = Series::whereHas('jobs')->get(); 
$seriesJob = $series->jobs; 
+0

我需要'TheSeries'的所有工作,這是行不通的。 – Coder

+0

編輯答案 –

+0

這會找到Series.id = 1的所有工作。我需要所有至少有工作的系列。 – Coder

0

有2種方式來做到這一點。第一個是使用像你已經開始的雄辯關係。爲了得到一個系列中所有您需要做的所有工作是:

$seriesCollection = TheSeries::all(); 
$seriesCollection->TheJobs(); 

第二種方法是在我看來更好。您將使用訪問器來檢索您想要的內容。 因此,在該系列機型,讓所有相關的一系列的作業只是做到以下幾點:

public function getSeriesJobsAttribute(){ 
    $job_series = DB::table('mSeriesJobs')->where('seriesID', $this->attributes['id'])->get(['jobID']); 
    $job = TheJobs::whereIn('id', $job_series)->get(); 
    return $job; 
} 

,然後在你看來只是通過$seriesCollection->series_jobs迭代,而在你的控制器,你只檢索$seriesCollection;

+0

當我嘗試你的第一個例子時,它說TheJobs()方法不存在:( – Coder

+0

you sho uld在你的系列模型 – xhulio

+0

中包含了該方法,但我沒有包括,但是它不起作用,因爲有多個記錄。 – Coder

1

從我所蒐集的內容中,我相信您正在尋找「查詢關係存在」(即Laravel Doc中的措辭)訪問模型的記錄,同時基於存在關係來限制結果。

在這種情況下,如果你需要一個簡單的雄辯的查詢,將選擇至少有一個TheJobs所有TheSeries,我相信你可以試試has

$TheSeries = App\TheSeries::has('TheJobs')->get(); 

另一種方式應太,就業:

$TheJobs = App\TheJobs::has('TheSeries')->get(); 

假設:所有模型關係都已被正確定義。

你可以找到更多關於「有」在這裏:https://laravel.com/docs/5.4/eloquent-relationships(在網頁中搜索「查詢的關係存在」請)