jeudi 31 mai 2018

Laravel local scope on eager load

Lets say I have three tables in DB (and three models).

  1. Destination (id, title, region_id)
  2. Region (id, title)
  3. Translations (id, region_id; nullable, destination_id; nullable, translated_value)

Then I have those relations and scopes defined:

  1. Destination

    public function getRegion(){
        return $this->belongsTo('App\Models\Region', 'region_id')->translate();}
    
    public function scopeTranslate($query){
        return $query->join('translations', function($join){
        $join->on('destinations.id', '=', 'translations.destination_id')
           ->where('language_code', app()->getLocale());
    })->select('destinations.*', 'translations.value as translated_title');}
    
    
  2. Region

    public function scopeTranslate($query){
        return $query->join('lm_translations', function($join){
        $join->on('regions.id', '=', 'lm_translations.region_id')
            ->where('language_code', app()->getLocale());
    })->select('regions.*', 'lm_translations.value as translated_title');}
    
    

Then I fetch destinations and eager load translations on both.

 $destinations = Destination::whereHas('getRegion')
     ->with('getRegion')->translate()->get();

Problem: Region gets translation from destination when eager loading, but if I load it usualy everything is fine.

I ran queries directly in DB and they are executed as they should, this means eager loading is not connecting relations correctly.

Where is the catch?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire