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
Product::with(["options.optionGroup"])->find(1);