我在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