mercredi 8 juin 2022

Unable to fetch results from hasManyJson Using staudenmeir / eloquent-json-relations

I have been working on two tables Category & Product. In Category Model I have a relationship like

class Category extends Model
{
  use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
  public function products(){

    return $this->hasManyJson(Product::class,'category_ids[]->id');
  }
}

In Products Model I have a relationship like

class Product extends Model
    {
      use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
      protected $casts = [
          'category_ids'=>'json', 
      ];
      public function products(){

        return $this->belongsToJson(Category::class,'category_ids[]->id');
      }
    }

Now in my controller when I'm doing trying to get count of each categories product, it is giving me Empty results, below is my controller code.

public function two_category()
{
    $list = Category::where('home_status', true)->get();
    foreach($list as $ls){
        echo $ls->name.'    '.count($ls->products).'<br>';
    }
    dd('ended');
   }

This is giving -

Category1 0

Category2 0

And finally this is how my column in product table looks like. Category id column in json



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire