首页 文章

多种多样的关系Laravel 5.4

提问于
浏览
0

我想在Laravel中 Build 多对多的多态关系 . (我是新手)

用户可以拥有许多配置文件类型配置文件类型类似于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);

它会按预期保存到数据透视表中,并且关系有效 .

profiles表看起来像这样:

id
user_id
profilable_id
profilable_type

现在问题是检索我的配置文件的模型集合 . 我得到了配置文件类型,但我没有得到网站管理员和ProjectManager .

所以问题是:在这个例子中我如何获得这个模型集合?

1 回答

  • 1

    你的模型结构如下:

    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');
        }
    }
    

    数据库架构:

    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) {
        //
    }
    

    实际上,您的 Profiles (网站管理员,管理员,项目管理员)是可以使用的 .

相关问题