Laravel关系-问题,答案和用户答案

问题描述

我有问题,我有3张桌子:

dbo.[YourTable   ]

示例记录:

questions

id | text

answers

id | question_id | text

user_answers

id | user_id | question_id | text

因此,我想知道是否存在在模型中没有RAW SQL(具有联接等)的关系的方法。例如,如下所示:

questions

1 | Gender
2 | Age (input type,answers not exist in answers table)
3 | What kind of pets do you have?

answers

1 | 1 | Male
2 | 2 | Female
3 | 3 | Cat
4 | 3 | Dog
5 | 3 | Parrot

user_answers

1 | 100 | 1 | 1
2 | 100 | 2 | 30
3 | 100 | 3 | 4
3 | 100 | 3 | 5

结果:


    $questions = Question::with('userAnswer')->where('user_id',100); 
    foreach($questions as $q)
    {
      echo $question->text;
      foreach($question->userAnswers as $ans)
      {
        echo $ans->text 
      }
    }

你知道我的意思吗?有什么想法吗? :) 谢谢您的关注!

已编辑:

这不起作用(关系stdAnswer为空),

Gender
 - male
Age
 - 30
What kind of pets do you have?
 - dog
 - parrot

这项工作:


    $questions = LucidStandardQuestion::with('userAnswers.stdAnswer')->find(x);

并在模型LucidStandarQuestion中:


    LucidStandardQuestion::with('userAnswers')->find(x)

并在模型LucidUserAnswer中:


    public function userAnswers()
    {
       $uid = 1576;
        
       return $this->hasMany(LucidUserAnswer::Class,'question_id')->where('user_id',$uid);
    }

解决方法

这是一个简单的hasMany关系:

class Question extends Model
{
    public function userAnswer()
    {
        return $this->hasMany(LucidUserAnswer::class,'question_id');
    }
}

现在您的代码可能如下:

$questions = Question::with(['userAnswer' => function($query)
{
    $query->where('user_id',100)->with('answer');
}])->get(); 

在LucidUserAnswer模型中,您应该建立关系

 class LucidUserAnswer extends Model
 {
     public function answer()
     {
         return $this->belongsTo(Answer::class,'text');
     }
 }

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...