在 Laravel 中联接表两次的语法


syntax to join a table twice in laravel

我正在尝试加入以下 3 个表。问题出在我想使用不正确的"AND"运算符将 posts.id 连接到shares.post_id的部分。这样做的正确语法是什么?

$sharedPosts = DB::table('shares')
            ->join('users', 'users.id', '=', 'shares.user_id')
            ->join('posts', 'posts.user_id', '=', 'users.id' , 'AND' , 'posts.id', '=', 'shares.post_id')
            ->where('shares.user_id', '=', $myFriends)
         ->get();

尝试别名:

$sharedPosts = DB::table('shares')
            ->join('users', 'users.id', '=', 'shares.user_id')
            ->join('posts as p1', 'p1.user_id', '=', 'users.id' , 'AND' , 'p1.id', '=', 'shares.post_id')
            ->join('posts as p2', 'p2.id', '=', 'shares.post_id')
            ->where('shares.user_id', '=', $myFriends)
         ->get();

不能在没有别名的情况下联接表两次。

虽然如果你的加入中有 2 个子句,我认为你应该按照文档中的去做:

$sharedPosts = DB::table('shares')
    ->join('users', 'users.id', '=', 'shares.user_id')
    ->join('posts as p1', , function($join){
        $join->on('p1.user_id', '=', 'users.id')
             ->on('p1.id', '=', 'shares.post_id')
    })
    ->join('posts as p2', 'p2.id', '=', 'shares.post_id')
    ->where('shares.user_id', '=', $myFriends)
->get();

编辑(一个帖子加入):

$sharedPosts = DB::table('shares')
    ->join('users', 'users.id', '=', 'shares.user_id')
    ->join('posts', , function($join){
        $join->on('posts.user_id', '=', 'users.id')
             ->on('posts.id', '=', 'shares.post_id')
    })
    ->where('shares.user_id', '=', $myFriends)
->get();