遵循我的数据库结构:
surveys
->id
->name
->version
answers
->id
->user_id
->question_survey_id
->content
questions
->id
->type
->title
question_survey
->id
->question_id
->survey_id
users
->id
->name
这些是我的模特
class Survey extends Model
{
public function questions(){
return $this->belongsToMany(Question::class);
}
}
class Question extends Model
{
public function surveys(){
return $this->belongsToMany(Survey::class);
}
}
// in User model
public function answers(){
return $this->hasMany(Answer::class);
}
// in Answer model
public function users(){
return $this->belongsTo(User::class,'user_id');
}
如何通过键question_survey_id
将 answer与问题表联系起来? question_survey
表的答案表是一对一关系...:)
如果问题不清楚,请不要投票并向我提问,谢谢
答案 0 :(得分:1)
由于您的数据库密钥是为Laravel假设定制的,因此您需要使用其他参数指定密钥名称。 See reference here。
class Question extends Model
{
// ...
public function answer(){
return $this->hasOne(Answer::class, 'question_survey_id');
}
// ...
}
class Answer extends Model
{
// ...
public function question(){
return $this->belongsTo(Question::class, 'question_survey_id');
}
// ...
}
答案 1 :(得分:0)
为question_survey
表创建一个名为QuestionSurvey
的模型,然后在Question
模型中添加另一个关系
问题模型
public function questionSurveys(){
return $this->hasMany(QuestionSurvey::class,'question_id');
}
QuestionSurvey模型
protected $table = "question_survey";
public function answer(){
return $this->hasOne(Answer::class,'question_survey_id');
}
现在您可以使用这些关系来获取
$questions = Question::with('questionSurveys.answer')->get();
foreach($questions as $question){
foreach($question->questionSurveys as $questionSurvey) {
echo "Answer=". $questionSurvey->answer->content;
}
}
答案 2 :(得分:0)
最佳关系方式
这样,您就不会在每次调查中都重复问题 两个相同的问题,但有两个不同的调查。
模型
调查
public function questions() {
return $this->belongsToMany(Question::class, 'survey_questions', 'survey_id', 'question_id');
}
问题
public function survey() {
return $this->belongsToMany(Survey::class, 'survey_questions', 'question_id', 'survey_id');
}
public function answers() {
return $this->hasMany(Answer::class)->where('survey_id', $this->survey->id);
}
答案
public function author() {
return $this->belongsTo(User::class, 'user_id');
}
数据库
tbl_surveys
tbl_questions
tbl_survey_questions
tbl_answers
tbl_users
我希望您知道下一步该怎么办。