mysql - Laravel 加入 3 个表

标签 mysql sql database join laravel

我正在构建一个类似 Twitter 的应用程序。有一个供稿,我只想在其中显示我关注的用户的帖子。

我尝试了连接的所有方法,但似乎没有任何效果。

我有 3 个表:UsersFollowersShares

表格看起来像这样:

用户:id

关注者:user_idfollower_id

分享:user_id

我需要得到的是“ALL Shares WHERE share.user_id = followers.follower_id” “ANDWHERE followers.user_id = users.id”

假设,users.id 是 3,我试过这个:

$shares = DB::table('shares')
        ->leftjoin('followers', 'shares.user_id', '=', 'followers.follower_id')
        ->leftjoin('users', 'followers.user_id', '=', 'users.id')
        ->where('users.id', 3)
        ->where('shares.user_id', 'followers.follower_id')
        ->get();

但它不起作用。

感谢任何帮助:)

最佳答案

我认为您的加入是错误的:

$shares = DB::table('shares')
    ->join('users', 'users.id', '=', 'shares.user_id')
    ->join('followers', 'followers.user_id', '=', 'users.id')
    ->where('followers.follower_id', '=', 3)
    ->get();

我还建议您将表命名为 follows,这样说 user has many followers through followsuser has many 感觉更自然关注者通过关注

示例

$shares = DB::table('shares')
    ->join('users', 'users.id', '=', 'shares.user_id')
    ->join('follows', 'follows.user_id', '=', 'users.id')
    ->where('follows.follower_id', '=', 3)
    ->get();

模型方法

我没有意识到您使用的是 DB:: 查询而不是模型。所以我正在修正答案并提供更多的清晰度。我建议你使用模型,对于那些刚开始使用框架,特别是 SQL 的人来说,它会容易得多。

模型示例:

class User extends Model {
    public function shares() {
        return $this->hasMany('Share');
    }
    public function followers() {
        return $this->belongsToMany('User', 'follows', 'user_id', 'follower_id');
    }
    public function followees() {
        return $this->belongsToMany('User', 'follows', 'follower_id', 'user_id');
    }
}
class Share extends Model {
    public function user() {
        return $this->belongsTo('User');
    }
}

模型使用示例:

$my = User::find('my_id');

// Retrieves all shares by users that I follow
// eager loading the "owner" of the share
$shares = Share::with('user')
    ->join('follows', 'follows.user_id', '=', 'shares.user_id')
    ->where('follows.follower_id', '=', $my->id)
    ->get('shares.*'); // Notice the shares.* here

// prints the username of the person who shared something
foreach ($shares as $share) {
    echo $share->user->username;
}

// Retrieves all users I'm following
$my->followees;

// Retrieves all users that follows me
$my->followers;

关于mysql - Laravel 加入 3 个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18388664/

相关文章:

php - 使用表单动态添加输入文件对象

sql - 如何获取表中每一列的空值计数

database - 根据 IANA 时区数据库,是否有位置 -> 时区名称的数据库

MySQL 更新越来越慢

mysql - 单个查询而不是多个 select 语句

mysql - 如何在单个查询mysql中选择多个表? (部分表还没有数据)

C# Entity Framework 保存具有多对多导航属性的记录

MySQL - min_word_length 2 或 3 - 需要计数

php - Sql Insert Into Select 语句 PDO

mysql - 使用 Laravel 语法的 Sql leftJoin 查询显示错误