从Laravel多对多数据透视表中显示值

问题描述:

我无法从多对多Laravel数据透视表中显示数据。数据透视表的设置是:从Laravel多对多数据透视表中显示值

characteristic_answers

id - user_id - characteristic_id - characteristic_option_id 
1  130   5      6 
1  130   5      7 
1  130   1      2 

模型characteristic_answer是:

/** 
* Get the characteristic for the charactersticanswer. 
*/ 
public function characteristic() 
{ 
    return $this->belongsTo(Characteristic::class); 
} 

/** 
* Get the option for the charactersticanswer. 
*/ 
public function characteristicOption() 
{ 
    return $this->belongsTo(CharacteristicOption::class); 
} 

,我现在必须遍历识别名和答案的观点是:

@foreach($user->characteristicAnswers as $characteristicAnswer) 
     @if(!$characteristicAnswer->characteristic->multiple) 
      <dt>{{$characteristicAnswer->characteristic->name}}</dt> 
      <dd>{{$characteristicAnswer->characteristicOption->name}}</dd> 
     @elseif($characteristicAnswer->characteristic->multiple) 
      <dt>{{$characteristicAnswer->characteristic->name}}</dt> 
      <dd>{{$characteristicAnswer->characteristicOption->name}}</dd> 
     @endif 
@endforeach 

但是这显示的答案如下:

**唯一的。 - >国王。

她从中取出一个罐子。 - >我,'说。

她等了一段时间。 - >但是,她这样做了。

她等了一段时间。 - >爱丽丝本人。

她等了一段时间。 - >爱丽丝再次..

测试kenmerk - >倪**

正如你可以看到她等着一些。特征重复4次,因为有三个答案。我希望特征名称在特征名称后面显示一次,三个答案在一个数组中显示。有人可以帮助我吗?

您应该使用'belongsToMany'关系。参考Laravel Many to Many Relation

数据透视表应包含两个表table1_id和table2_id(表名,后跟下划线和id)的ID。

而对于独特的价值使用DISTINCT应该工作。

我希望这会对你有用。干杯。