laravel 8 ,我有3个表属性和值和广告之间的关系

laravel 8 , I have a relationship between 3 tables attribute and value and ad

广告模型

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');
}

属性模型

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');
}

属性值模型

  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');
}

这样,在数据透视表中保存属性和值以及广告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);
    }

一切正常,我将 (id) 保存在数据透视表 table 中。我意识到错误的想法,因为我将拥有一个具有多个值的属性。我该如何解决这个问题?

return $请求;

      {
      "attribute_id": [
                "1",
               "2",
                "3"
                     ],
       "attvalue_id": [
           "1",
           "4",
           "7",
           "8"
                    ],

但只保存了

    attrvalue_id  |attribute_id  |ad_id 
     1            |1             |6
     4            |2             |6
     7            |3             |6

解决了,我将枢轴 table 更改为

    attrvalue_id   |ad_id 
     1             |83
     4             |83
     7             |83
     8             |83

并且我在属性和 attrValue 之间得到属性形式 elquent

$ad = Ad::with('images','attvalues.attribute')->find($id);