nekooee
1 week ago

how to define a convenient shortcut for accessing distant relations, between “OneToMany” and “manyToMany polymorphic”?

Posted 1 week ago by nekooee

I have three models: "Article", "ArticleTranslation", Tag".

Article translations in different languages are stored in the ArticleTranslation.

The "Article" model has a one-to-many relationship with the "ArticleTranslation" model and the "ArticleTranslation" model has a many-to-many polymorphic relationship with the "Tag" model. I need to define a convenient shortcut to easily gather all article tags for a given article and I need to define a convenient shortcut to easily gather all the articles that have the given tag.

Relations

for translate article I use laravel-translatable package.

tables of this relationships: articles:

id - integer
article_translations:
id - integer
article_id - integer
locale - string
title - string
slug - string
tags:
id - integer
slug - string
taggables:
tag_id - integer
taggable_id - integer
taggable_type - string

Article Model:

class Article extends Model
{
    use Translatable;
    public $translatedAttributes = ['title', 'slug', 'description', 'body'];
}

ArticleTranslation Model:

class ArticleTranslation extends Model
{
    use Sluggable;
    public $timestamps = false;
    protected $fillable = ['title', 'slug', 'description', 'body'];

    public function sluggable()
    {
        return [
            'slug' => [
                'source' => 'title',
            ],
        ];
    }
   
    public function tags()
    {
        return $this->morphToMany(Tag::class, 'taggable');
    }
}

Tag Model:

lass Tag extends Model
{
    use Sluggable;
    protected $fillable = ['name'];
    public function sluggable()
    {
        return [
            'slug' => [
                'source' => 'name',
            ],
        ];
    }

    public function articleTranslate()
    {
        return $this->morphedByMany(ArticleTranslation::class, 'taggable');
    }
}

Please sign in or create an account to participate in this conversation.