samedi 22 décembre 2018

How to get nested relation value with Eager Loading using hasManyThrough?

I want to retrieve tags related to each model without loading all columns of intermediate tables. I want to display tags on index page. Please tell me if any solution exist for this scenario.

I tried with hasManyThrough relationship to get tags but its not working because of polymorphic index table.

(Table Name => Table Columns)

food_index => id, description, food_type, food_id

fruits => id, description, price, availability

vegetables => id, description, price, availability, calories

cereal => id, description, price, availability, brand

tags => id, tag

(pivot table) taggable => id, tag_id, taggable_type, taggable_id

Models =>

class Fruit extends Model
{

   public function index()
   {
      return $this->morphOne('App\FoodIndex', 'indexable', 'food_type', 'food_id');
   }

   public function tags() {

      return $this->morphToMany('App\Tag', 'taggable');
   }
}

class Vegetable extends Model
{

   public function index()
   {
      return $this->morphOne('App\FoodIndex', 'indexable', 'food_type', 'food_id');
   }

   public function tags() {

       return $this->morphToMany('App\Tag', 'taggable');
   }
}

class Cereal extends Model
{

    public function index()
    {
        return $this->morphOne('App\FoodIndex', 'indexable', 'food_type', 'food_id');
    }

    public function tags() {

        return $this->morphToMany('App\Tag', 'taggable');
    }
}

class Tag extends Model
{

    public function fruits() {

        return $this->morphedByMany('App\Fruit', 'taggable');
    }
    public function vegetables() {

        return $this->morphedByMany('App\Vegetable', 'taggable');
    }
    public function cereals() {

        return $this->morphedByMany('App\Cereal', 'taggable');
    }
}

class FoodIndex extends Model
{

    public function owner()
    {
        return $this->morphTo("owner", "food_type", "food_id");
    } 
    public function tags()
    {
        // return $this->hasManyThrough("App\Tag", "App\FoodIndex", "food_id", 'food_type', "taggable_id", "taggable_type");
        // return $this->hasManyThrough('App\Tag', $this->food_type, 'id', 'id');
    }
}

Code in controller =>

    $index = FoodIndex::whereRaw("MATCH description AGAINST (? IN BOOLEAN MODE)", [$this->fullTextWildcards($term)])->with([
        'tags'
        ])->simplePaginate(5);

I expect $index->tag property to return the tag associated with each food item but I am getting errors



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire