Laravelプロジェクトにはsurvey
とquestion
という2つのテーブルがあります。私は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);
}
しかしquestion_idが1のとき、私はループ$survey->questions
て、それが唯一の行を返しているとき?私は間違って何をしていますか?
あなたのアンケートと質問表には関係がありません。次の点を確認してください:https://laravel.com/docs/5.5/eloquent-relationships#has-many-through –
@MahfuzShishir Mortezaによって提案された多対多の多くの関係を使用していただきありがとうございます。 – xylar