2017-09-22 22 views
0

私はLaravelに多対多の関係を確立したいと思います。 (私は初めてです)多対多多型関係Laravel 5.4

ユーザは多くのプロファイルタイプを持つことができます プロファイルタイプはAdmin、Webmaster、ProjectManagerのようなものです。 プロファイルのための多相関係とピボットテーブルを作成しました。

class User { 

    public function profiles(){ 
     return Profile::where('user_id', $this->id); 
    } 

} 

class Webmaster { // and class Admin, Projectmanager 

    public function profiled(){ 
     return $this->morphToMany(Profile::class, 'profileable'); 
    } 

    public function saveToUser($user) 
    { 
     $profile = new Profile; 
     $profile->user_id = $user->id; 
     return $this->profiled()->save($profile); 
    } 

} 

今私は、対応するユーザにモデルを保存することができます。

$projectManager->saveToUser($user); 
$webmaster->saveToUser($user); 

ピボットテーブルに期待どおりに保存され、関係が有効です。

プロファイル表のようになります。

id 
user_id 
profilable_id 
profilable_type 

今の問題は、私のプロファイルのモデルコレクションを取得しています。私はプロファイルの種類を取得しますが、私はWebmasterとProjectManagerを取得しません。

質問:私はこのモデルコレクションをこの例でどのように取得するのですか?

class Webmaster extends Model 
{   
    public function users() 
    { 
     return $this->morphToMany('App\Profile', 'userable'); 
    } 
} 

class Admin extends Model 
{   
    public function users() 
    { 
     return $this->morphToMany('App\Profile', 'userable'); 
    } 
} 

// and ProjectManager, .... 

ユーザーモデル::

class User extends Model 
{   
    public function webmasters() 
    { 
     return $this->morphedByMany('App\Webmaster', 'userable'); 
    } 

    public function admins() 
    { 
     return $this->morphedByMany('App\Admin', 'userable'); 
    } 
} 

データベース・スキーマ:

+0

多対多多相関係を言う方が良いです。 –

+0

@MortezaRajabiありがとう、私は編集しました。あなたはお尻の上で私を助けることができますか? – HerrWalter

+1

はい、私はあなたの質問に少しでも変更して答えを分かりやすくするために名前をつけます。 –

答えて

1

あなたのモデルの構造は次のようになるだろう

:今

webmasters 
    id - integer 
    ... 

admins 
    id - integer 
    ... 

users 
    id - integer 
    ... 

userables 
    user_id - integer 
    userable_id - integer 
    userable_type - string 

、あなたは関係を取得することができます

$webmaster = App\Webmaster::find(1); 
// retrieve users of a profile 
foreach ($webmaster->users as $user) { 
    // 
} 


$user = App\User::find(1); 
// retrvieve webmaster profiles of a user 
foreach ($user->webmasters as $webmasters) { 
    // 
} 

実際、あなたのプロフィール(webmaster、admin、projectmanager)はユーザーフレンドリーです。

+0

あなたのawnserありがとう!それは非常に有用です。 私は達成したいことを明確にしていないかもしれません。 ユーザーは1人のWebmasterと1人の管理者のコレクションを持つことができます $ user-> profiles()// Retrieve [Webmaster、Admin] – HerrWalter

+1

よろしくお願いします。私は私の答えを編集するつもりです。 –

+0

これを行う方法はないようです。それらは異なるテーブル構造を持ち、1つのクエリでこれらのテーブルを介してクエリを実行することは実用的ではないためです。それぞれに1つの関係を設定するか、上記の答えを使用する方が良いです。 –