jeudi 26 mai 2016

Many to many polymorphic with multiple sub-models sync() method

I have two sub-model Category and Tag which extends the Term model. Both sub models are have many-to-many polymorphic relation to the Post model with pivot table termables.

// Post.php
class Post extends Model
{
    public function categories()
    {
        return $this->morphToMany(Category::class, 'termable', 'termables', 'termable_id', 'term_id');
    }

    public function tags()
    {
        return $this->morphToMany(Tag::class, 'termable', 'termables', 'termable_id', 'term_id');
    }
}

// Term.php
class Term extends Model
{

}

// Category.php
class Category extends Term
{
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new TypeScope('category'));
    }

    public function posts()
    {
        return $this->morphedByMany(Post::class, 'termable', 'termables', 'term_id', 'termable_id')
    }
}

// Tag.php
class Tag extends Term
{
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new TypeScope('tag'));
    }

    public function posts()
    {
        return $this->morphedByMany(Post::class, 'termable', 'termables', 'term_id', 'termable_id')
    }
}

When updating the categories and tags together, either tags got removed when updating the categories or categories got removed when updating the tags

Looks like Laravel doesn't check first what is the model of term_id that I've actually declared by $this->morphToMany(Category::class, 'termable', 'termables', 'termable_id', 'term_id'); before removing and just simply remove everything by termable_type.

The possible solution that might works is by separate the pivot table for each sub model into categorizables and taggables instead of using single termables pivot table. But it will makes my database full of pivot tables if I decided to create another set of Term's sub-models.

Any solution how to make it works without separating the pivot table?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire