2017-09-25 103 views
0

我在Laravel項目中有兩個表surveyquestion。我想創建一個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返回行?我做錯了什麼?

+1

您的調查和問題表不包含任何關係。檢查:https://laravel.com/docs/5.5/eloquent-relationships#has-many-through –

+0

@MahfuzShishir感謝使用Morteza建議的多對多關係解決了我的問題。 – xylar

回答

1

這是一個多對多的關係。

測量模型

public function questions() 
{ 
    return $this->belongsToMany(Question::class, 'survey_question'); 
} 

問題型號

public function surveys() 
{ 
    return $this->belongsToMany(Survey::class, 'survey_question'); 
} 

然後你就可以

$survey = Survey::with('questions')->find($id); 

@foreach($survey->questions as $question) 
    //... 
@endforeach 
+0

@xylar不要忘記投票。 –

0

請參考docs

繼結構hasManyThrough你需要有結構這樣

調查 ID - 整數 名字 - 字符串

問題 ID - 整數 survey_id - 整數 名字 - 字符串

SurveyQuestion id - 整數 question_id - 整數 標題 - 字符串

但是你沒有在中間表的外鍵解決這個問題第一,那麼我想你會擺脫這個問題的。