如何使用 Laravel 查询生成器编写此查询?

How to write this query using Laravel query builder?

我是 laravel 的新手。这是我的查询,它过滤掉没有任何问题(问题)或问题没有任何答案的测验。但我不确定如何使用 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
             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) {
    //
}
SELECT 
    *, SUM(num_hr) AS total_hr, attendances.empID AS empid 
FROM attendances 
LEFT JOIN addsalaryemployees ON addsalaryemployees.empID=attendances.empID 
LEFT JOIN positions ON positions.id=addsalaryemployees.empPosition 
GROUP BY attendances.empID 
ORDER BY addsalaryemployees.empFirstName ASC