简体   繁体   中英

Many To Many Polymorphic Relations Laravel 5.4

I'd like to establish a many to many polymorphic relation in Laravel. (I'm new to it)

A user can have many profile types Profile types are like Admin, Webmaster, ProjectManager. I created a polymorphic relation and a pivot table for the profiles.

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

}

Now I can save the models to the corresponding User.

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

It gets all saved to the pivot table as expected and the relations are valid.

profiles table looks like this:

id
user_id
profilable_id
profilable_type

Now the problem is retrieving a model collection of my profiles. I get the Profile types, but I dont get the Webmaster and ProjectManager.

So the question is: how do I get this model collection in this example?

Your model structure is going to be like:

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, ....

User Model:

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

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

Database schema:

webmasters
    id - integer
    ...

admins
    id - integer
    ...

users
    id - integer
    ...

userables
    user_id - integer
    userable_id - integer
    userable_type - string

Now, you can retrieve the relations:

$webmaster = App\Webmaster::find(1);

// retrieve users of a profile
foreach ($webmaster->users as $user) {
    //
}

$user = App\User::find(1);

// retrieve webmaster profiles of a user
foreach ($user->webmasters as $webmasters) {
    //
}

Actually, your profiles (webmaster, admin, projectmanager) are userable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM