我在Laravel项目中有两个表survey
和question
。我想创建一个hasManyThrough雄辩的关系,这样我就可以遍历属于该调查的所有问题。Laravel hasManyThrough - 没有返回所有预期结果
调查表:
----------------
| id | title |
----------------
| 1 | fruit |
----------------
问表:
----------------
| id | title |
----------------
| 1 | apple? |
| 3 | banana? |
| 4 | kiwi? |
| 5 | pear? |
----------------
SurveyQuestion表:
--------------------------------
| id | survey_id | question_id |
--------------------------------
| 1 | 1 | 1 |
| 1 | 1 | 4 |
| 1 | 1 | 5 |
--------------------------------
在我的调查型号目前,我有以下
public function questions()
{
return $this->hasManyThrough(
Questions::class,
SurveyQuestion::class,
'question_id', // Foreign key on surveyquestion table...
'id', // Foreign key on questions table...
'id', // Local key on survey table...
'survey_id' // Local key on surveyquestion table...
);
}
,在我SurveyQuestion模型我有:
public function survey()
{
return $this->belongsTo(Survey::class);
}
public function question()
{
return $this->belongsTo(Questions::class);
}
然而,当我遍历$survey->questions
它只有在question_id是1返回行?我做错了什么?
您的调查和问题表不包含任何关系。检查:https://laravel.com/docs/5.5/eloquent-relationships#has-many-through –
@MahfuzShishir感谢使用Morteza建议的多对多关系解决了我的问题。 – xylar