0

how to get hasmany relation inside another relation in Laravel

i want to get product optionGroup with product options

i made this

    $try1 = Product::with(["optionGroups.options"])->find(1);

but this return all group options

i want to get product optionGroup with product options only

i want it to be like

{
  "title": "product name",
  "optionGroups": [
    {
      "name": "Size",
      "options": [
        {
          "name": "XL",
          "price": 1200
        },
        {
          "name": "L",
          "price": 1000
        }
      ]
    }
  ]
}

models

class Product extends Model
{
    public function options()
    {
        return $this->hasMany(Option::class, 'product_id');
    }
    public function optionGroups()
    {
        return $this->belongsToMany(OptionGroup::class, 'options')->groupBy("id");
    }
}

class Option extends Model
{
    public function product()
    {
        return $this->belongsTo(\App\Models\Product::class, 'product_id', 'id');
    }
    public function optionGroup()
    {
        return $this->belongsTo(\App\Models\OptionGroup::class, 'option_group_id', 'id');
    }
}

class OptionGroup extends Model
{
    public $table = 'option_groups';
    public $fillable = [
        'name'
    ];
    public function options()
    {
        return $this->hasMany(Option::class, 'option_group_id');
    }
}

Schema::create('products', function (Blueprint $table) {
    $table->id('id');
    $table->string('title');
});
Schema::create('options', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name', 127);
    $table->double('price', 8, 2)->default(0);
    $table->integer('product_id')->unsigned();
    $table->integer('option_group_id')->unsigned();
});
Schema::create('option_groups', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name', 127);
});

please help me

yemenpoint
  • 167
  • 3
  • 5

2 Answers2

2
Product::whereHas('optionGroups', function($query){
     $query->with(['options']);
})->first();
Bipin Regmi
  • 137
  • 1
  • 11
0

Try adding this to your Product model

public function optionGroupsAndOptions()
{
    return $this->optionGroups->with('options')->where('product_id', $this->id);
}

then

$try1 = Product::with("optionGroupsAndOptions")->find(1);
Basharmal
  • 1,313
  • 10
  • 30