2017-09-25 105 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 - 整数 标题 - 字符串

但是你没有在中间表的外键解决这个问题第一,那么我想你会摆脱这个问题的。