Php 如何使用Laravel查询生成器编写此查询?
我是拉威尔的新手。这是我的查询,它过滤掉了没有问题或问题没有答案的测验。但我不知道如何使用laravel查询生成器正确编写它。考虑到我正在使用eloquent建立人际关系,如果我能使用laravel eloquent获得同样的结果,那会更好Php 如何使用Laravel查询生成器编写此查询?,php,mysql,laravel,eloquent,laravel-query-builder,Php,Mysql,Laravel,Eloquent,Laravel Query Builder,我是拉威尔的新手。这是我的查询,它过滤掉了没有问题或问题没有答案的测验。但我不知道如何使用laravel查询生成器正确编写它。考虑到我正在使用eloquent建立人际关系,如果我能使用laravel eloquent获得同样的结果,那会更好 SELECT DISTINCT q.id, q.content FROM m_quiz q RIGHT JOIN (SELECT DISTINCT p.quiz_id as id FROM m_problem p
SELECT DISTINCT q.id, q.content
FROM m_quiz q
RIGHT JOIN (SELECT DISTINCT p.quiz_id as id
FROM m_problem p
RIGHT JOIN m_answer_choice a
ON p.id = a.problem_id) problem
ON q.id = problem.id
ORDER BY q.id;
没有测试过,但我想应该是这样的
DB::table('problems')->selectRaw('m_problem.*, DISTINCT m_problem.quiz_id as id')
->join('m_answer_choice', 'm_problem.id', '=', 'm_answer_choice.problem_id')
->groupBy('m_problem.id')
->get();
但如果你能像这样做会更好
namespace App;
use Illuminate\Database\Eloquent\Model;
class Problem extends Model
{
/**
* Get the comments for the blog post.
*/
public function answerChoices()
{
return $this->hasMany('App\AnswerChoices');
}
}
$answerChoices= App\Problem::find(1)->answerChoices;
foreach ($answerChoices as $answerChoice) {
//
}
然后做一些类似的事情
namespace App;
use Illuminate\Database\Eloquent\Model;
class Problem extends Model
{
/**
* Get the comments for the blog post.
*/
public function answerChoices()
{
return $this->hasMany('App\AnswerChoices');
}
}
$answerChoices= App\Problem::find(1)->answerChoices;
foreach ($answerChoices as $answerChoice) {
//
}
你最好选择关系模型?