how retrieve relation between two model that other models have polymorphic relation with both of them

57 Views Asked by At

I have these two models: Tag and Translate, I have these tables: tags, translates, translatables, Tag model uses translatable.

my table columns is like this:

  translates:                      translatables:                            tags: 
id     name  lang   |  translate_id    translatable_id     translatable_type |  id
--     ----  ----   |  -------------   ---------------     ----------------- |  --
                    |                                                        |

I want to write a function to get current translation of tag based on app locale which means I should query on translates tables based on translatables table data and using translateble_id and translatable_type find id in the translate table and get the name based on lang. do you know how i can do this?

this is translatable trait:

trait Translatable{
    public function translates(){
        return $this->morphToMany(Translate::class,'translatable','translatables','translatable_id','translate_id');
    }
} 

and this is how I get locale:

$locale=app()->getLocale();

I get tags translates with querybuilder like:

$locale=app()->getLocale();
$tags=DB::table('translates as T')
       ->where('lang','=',$locale)
       ->join('translatables as R','R.translate_id','=','T.id')
       ->where('R.translatable_type','=','App\Models\Tag')
       ->join('tags as M','R.translatable_id','=','M.id')
       ->get();

but i want to use a function in model and eloquent.

0

There are 0 best solutions below