Laravel Fluent Query Builder Join with subquery

前端 未结 7 638
天涯浪人
天涯浪人 2020-11-27 13:03

Okay after hours of research and still using DB::select I have to ask this question. Because I am about to trough my computer away ;).

I want to get the last input o

相关标签:
7条回答
  • 2020-11-27 13:33

    I am on Laravel 7.25 and I don't know if it supports on previous versions or not but Its pretty good.

    Syntax for the function:

    public function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false)

    Example:

    Showing/Getting the user ID and the total number of posts by them left joining two tables users and posts.

            return DB::table('users')
                ->joinSub('select user_id,count(id) noOfPosts from posts group by user_id', 'totalPosts', 'users.id', '=', 'totalPosts.user_id', 'left')
                ->select('users.name', 'totalPosts.noOfPosts')
                ->get();
    

    Alternative:

    If you don't wanna mention 'left' for leftjoin then you can use another prebuilt function

        public function leftJoinSub($query, $as, $first, $operator = null, $second = null)
        {
            return $this->joinSub($query, $as, $first, $operator, $second, 'left');
        }
    

    And yeah, it actually calls the same function but it passes the join type itself. You can apply the same logic for other joins i.e. righJoinSub(...) etc.

    0 讨论(0)
提交回复
热议问题