我如何在laravel中链接关系表,我在stackoverflow上找到但没有完全理解

时间:2018-08-03 03:14:27

标签: laravel

遵循我的数据库结构:

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表的答案表是一对一关系...:)

如果问题不清楚,请不要投票并向我提问,谢谢

3 个答案:

答案 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)

最佳关系方式

  1. 调查属于到很多问题
  2. 问题属于多调查
  

这样,您就不会在每次调查中都重复问题   两个相同的问题,但有两个不同的调查。

  1. 问题有很多答案,其中survey_id =问题->调查
  2. 答案属于用户

模型

调查

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

  • id
  • 调查名称

tbl_questions

  • id
  • 问题

tbl_survey_questions

  • id
  • survey_id
  • question_id

tbl_answers

  • id
  • user_id
  • answer
  • question_id
  • survey_id

tbl_users

  • id
  • 名称

我希望您知道下一步该怎么办。