Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/229.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用Laravel查询生成器编写此查询?_Php_Mysql_Laravel_Eloquent_Laravel Query Builder - Fatal编程技术网

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

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

我是拉威尔的新手。这是我的查询,它过滤掉了没有问题或问题没有答案的测验。但我不知道如何使用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) {
    //
}
然后做一些类似的事情

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) {
    //
}

你最好选择关系模型?