我想通过三个表来创建一个关系。
我的关系-用户->回答->问题
答案模型
public function question()
{
return $this->hasMany('App\Question','id');
}
问题模型
public function answer()
{
return $this->belongsTo('App\Question','question_id');
}
用户模型
public function maritalStatus()
{
return $this->belongsTo('App\Answer','marital_status');
}
视图
{{ $user->maritalStatus->question->label }}
错误
未定义属性: Illuminate\Database\Eloquent\Collection::$label
谢谢
发布于 2016-09-08 21:58:00
我想你把关系交换了。
以下是对我来说有意义的:Answer belongsTo Question
和Question hasMany Answer
。
class Answer
{
public function question()
{
return $this->belongsTo('App\Question');
}
}
class Question
{
public function answers()
{
return $this->hasMany('App\Answer');
}
}
在您的示例中,$answer->question
是一个集合(而不是单个模型),因为您将它定义为hasMany
关系而不是belongsTo
。
因此,如果您想保持您现在的关系(我不希望这样,因为一次回答许多问题的方法与相反的方法相比非常少见),您需要在您的{{ $user->maritalStatus->question->first()->label }}
中添加一个{{ $user->maritalStatus->question->first()->label }}
。但在这种情况下,更确切地说是questions
(复数),然后它可能更明显的…
https://stackoverflow.com/questions/39404589
复制