简体   繁体   中英

Polymorphic many-to-many relation

I couldn't get related models in many-to-many polymorphic relation saved into database.

$photo = Photo::find(1);
$photo->articles()->attach(2);

something like this wouldn't work and gives

error: Call to undefined method Illuminate\\Database\\Query\\Builder::articles()'

How to do it the right way?

Models

class Tag extends Eloquent
{
    public function articles()
    {
        return $this->morphedByMany('Article', 'taggable');
    }

    public function photos()
    {
        return $this->morphedByMany('Photo', 'taggable');
    }
}
class Article extends Eloquent
{
    public function tags()
    {
        return $this->morphToMany('Tag', 'taggable');
    }
}

class Photo extends Eloquent
{
    public function tags()
    {
        return $this->morphToMany('Tag', 'taggable');
    }
}

Finally got it working... Basically it's polymorphism + many to many relationship combined. I thought it don't require tags table. Taggables table acts as pivot table and tags is the table which contains Tag objects that connect models based on pivot table (taggables table)

Morphing does not Support Many To Many, it is actually a one to one association , it is used to create relations between different Models, so for example if you have Tag Model, the tag model could relate to many different occasions, it could relate to Page Model, to Post Model, to Product Model etc, what it actually achieves is that it allows you to relate to that other model without explicity defining the related model in the DB level, for instance a Tag model could be associated with a Post Model, but then you would need to define in the db, a post_id foreign key, with Polymorphic relations you can relate to that Post Model, without defining the model on the DB level as a specific field:

Polymorphic relations allow a model to belong to more than one other model, on a single association

And in Django Documentation you can clearly see how this association works:

staff
    id - integer
    name - string

orders
    id - integer
    price - integer

photos
    id - integer
    path - string
    imageable_id - integer
    imageable_type - string

The association from above is: 1 Photo relates to 1 Other Model, but with a different concrete implementation* thus a photo can belong to Staff, or it can belong to an order.

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