Laravel如何进行这种关系查询

时间:2016-06-10 09:16:15

标签: php mysql laravel join eloquent

我有一个像这样的当前数据库设置: enter image description here

我有一个用户模型/投票模型/组模型/投票子项目模型。 用户和投票之间存在多对多的关系,并且用户和子项之间存在多对多的关系。

我希望得到一个 ll在时间戳创建的投票到属于一组组ID的东西,其中特定用户在user_vote_casts表中没有条目

我怎样才能在laravel中做到这一点?

在mysql中,我认为这是正确的:

SELECT * from vote left join user_vote_casts on vote.id = user_vote_casts.vote_id where user_vote_casts.user_id IS NULL AND vote.id IN (12,3142,512,51,12,1) ;

2 个答案:

答案 0 :(得分:3)

根据您的SQL查询进行Laravel查询:

$users = DB::table('vote')
            ->leftJoin('user_vote_casts', 'vote.id', '=', 'user_vote_casts.vote_id')
            ->select('vote.*')
            ->where('user_vote_casts.user_id','')
            ->whereIN('vote.id',[12,3142,512,51,12,1])
            ->get();

答案 1 :(得分:0)

我最终做的是:

    $vote = Vote::leftJoin('user_vote_casts', function ($join) {
                $join->on('vote.id', '=', 'user_vote_casts.vote_id');
            })->whereNull('user_vote_casts.user_id')
->orderBy('vote.updated_at', 'DESC')
->take(30)->get();