laravel 8 , I have a relationship between 3 tables attribute and value and ad
ad model
public function attvalues()
{
return $this->belongsToMany(Attrvalue::class,'attribute_ad')-
>withPivot('attribute_id');
}
public function attributes()
{
return $this->belongsToMany(Attribute::class,'attribute_ad')->withPivot('attrvalue_id');
}
Attribute model
public function attvalues()
{
return $this->belongsToMany(Attrvalue::class,'attribute_ad')->withPivot('ad_id');
}
public function ads()
{
return $this->belongsToMany(Ad::class,'attribute_ad')->withPivot('attrvalue_id');
}
Attrvalue model
public function attributes()
{
return $this->belongsToMany(Attribute::class,'attribute_ad')->withPivot('ad_id');
}
public function ads()
{
return $this->belongsToMany(Ad::class,'attribute_ad')->withPivot('attribute_id');
}
In this way, save attribute and value and ad in pivot table
if (count($request->input('attribute_id')) > 0) {
$date2 = array();
foreach ($request->input('attribute_id') as $key => $value) {
$adAttribute = array(
'ad_id' => $ad->id,
'attribute_id' => (int)$request->attribute_id[$key],
'attrvalue_id' => (int)$request->attvalue_id[$key],
);
array_push($date2, $adAttribute);
}
$ad->attributes()->attach($date2);
}
Everything is fine and I was saving the (id) in the pivot table. I realized the wrong idea because I will have an attribute that takes multiple values. How do I solve the problem?
return $request;
{
"attribute_id": [
"1",
"2",
"3"
],
"attvalue_id": [
"1",
"4",
"7",
"8"
],
but only saved
attrvalue_id |attribute_id |ad_id
1 |1 |6
4 |2 |6
7 |3 |6
solved i changed pivot table to
attrvalue_id |ad_id
1 |83
4 |83
7 |83
8 |83
and i get attribute form elquent between attribute and attrValue
$ad = Ad::with('images','attvalues.attribute')->find($id);