gpt4 book ai didi

mysql - Laravel 加入 3 个表

转载 作者:IT老高 更新时间:2023-10-28 23:50:30 25 4
gpt4 key购买 nike

我正在构建一个类似 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com