2017-05-19 12 views
0

Laravel(5.4)のピボット(中間)テーブルの列を作成し、その結果をフィルタリングするにはどうすればよいですか?Laravel(5.4)の中間(ピボット)テーブル列をフィルタリング/選択する方法

私は2つのモデルFilmsとCastAndCrewを持っています。 CastAndCrewは映画で働く様々な監督、プロデューサー、俳優です。ピボットテーブルは、CastAndCrewメンバーとFilmの間の関係のタイプを定義する必要があります。明らかに、例えば誰かが次のようになる可能性があります。 1つの映画の俳優と別の映画のプロデューサーであるため、CastAndCrewテーブルのエントリにこれを定義することはできません。だから私はピボットテーブルで関係を定義する必要があると仮定しますが、私はこれを正確に行う方法がわかりません。私がこれまで持っている:

class Film extends Model 
{ 
    protected $fillable = array('filmtitle', 'description'); 

    public function List_Directors() 
     { 
     return $this->belongsToMany('App\CastAndCrew')->withPivot('type')->wherePivot('type', 'director'); 
     } 

    public function List_Actors() 
     { 
     return $this->belongsToMany('App\CastAndCrew')->withPivot('type')->wherePivot('type', 'actor'); 
     } 
} 

と新しいCastAndCrewメンバーがサイトに追加されます

class CastAndCrew extends Model 
{ 
    protected $fillable = array('firstname', 'lastname'); 

    public function List_Films_With_Director() 
     { 
     return $this->belongsToMany('App\Film')->withPivot('type')->wherePivot('type', 'director'); 
     } 

    public function List_Films_With_Actor() 
     { 
     return $this->belongsToMany('App\Film')->withPivot('type')->wherePivot('type', 'actor'); 
     } 
} 

を、私は、例えばを添付する方法を使用することを意図しています新しいディレクターを追加する:

$newcastcrew->CastAndCrew::create(['firstname' => Request::get('firstname'), 'lastname' => Request::get('lastname')]); 

$newcastcrew->List_Films_With_Director()->attach($filmID, ['type' => 'director']); 

1.)そうですか?

2.)->withPivot('type')はピボットテーブルに 'タイプ'列を作成していますか?そうでない場合は、どこで定義しますか?

2.)おそらく、の->wherePivot('type', 'director')句は、その映画の監督であるCastAndCrewメンバーを返しますか? (私が欲しいものです)

訂正ありがとう!あなたのアイデアやロジック

おかげ

+1

すべてのことは問題ありません。 –

答えて

1

は完全に罰金です。タイプ条件なしで関係を追加して、ユーザーのすべてのフィルムとすべてのキャストとクルーを取得することができます。あなたはまた、あなたの方法と関係をよりよく名づける必要があります。私はあなたのためのコードをきれいにしました。あなたが好きならこれを自由に使ってください。

class Film extends Model 
{ 
    protected $fillable = array('filmtitle', 'description'); 

    public function castAndCrew() 
    { 
     return $this->belongsToMany('App\CastAndCrew')->withPivot('type'); 
    } 

    public function directors() 
    { 
     return $this->castAndCrew()->wherePivot('type', 'director'); 
    } 

    public function actors() 
    { 
     return $this->castAndCrew()->wherePivot('type', 'actor'); 
    } 
} 

class CastAndCrew extends Model 
{ 
    protected $fillable = array('firstname', 'lastname'); 

    public function films() 
    { 
     return $this->belongsToMany('App\Film')->withPivot('type'); 
    } 

    public function filmsAsDirector() 
    { 
     return $this->films()->wherePivot('type', 'director'); 
    } 

    public function filmsAsActor() 
    { 
     return $this->films()->wherePivot('type', 'actor'); 
    } 
} 
+0

これは非常に参考になりました、ありがとうございます! –

関連する問題