加入Laravel的3张桌子?

时间:2015-08-12 07:09:54

标签: php laravel

我有3张桌子:问题答案& 评分

我想将answers表与questions表一起加入questions.id = answers.question_idratings表到answers表格answers.id = ratings.answer_id

但它会返回null

 $allQuestionWithAnswerAndRating = DB::table('questions')->orderBy('questions.id','desc' )
    ->join( 'answers', 'questions.id' , '=' , 'answers.question_id' )
    ->where('answers.user_id', '=' ,Auth::user()->id )
    ->join( 'ratings', 'answers.id' , '=' , 'ratings.answer_id')
    ->select( 'questions.id as id' , 'questions.body as question' , 'answers.body as answer' ,'answers.user_id as user_id')
    ->get();

此代码有什么问题?

由于

1 个答案:

答案 0 :(得分:1)

查看eloquent documentation的高级联接语句部分。

  

您还可以指定更高级的join子句。要开始,通过   一个Closure作为join方法的第二个参数。关闭   将收到一个允许您指定的JoinClause对象   对join子句的约束

     

...

     

如果您想在联接中使用“where”样式条款,您可以   在连接上使用where和orWhere方法。而不是比较两个   列,这些方法会将列与值进行比较:

对于你的陈述,看起来像这样:

DB::table('questions')
    ->join( 'answers', function($join) {
        $join->on('questions.id' , '=' , 'answers.question_id')
             ->where('answers.user_id', '=' , Auth::user()->id);
    })->join( 'ratings', 'answers.id' , '=' , 'ratings.answer_id')
    ->select(
        'questions.id as id', 
        'questions.body as question', 
        'answers.body as answer',
        'answers.user_id as user_id'
    )->get();