Pli*_* Pl 20 mysql sql database join laravel
我正在构建一个类似Twitter的应用程序.有一个Feed,我只想显示我关注的用户的帖子.
我用连接尝试了一切,但似乎没有任何效果.
我有3个表:Users,Followers,Shares
表格如下所示:
用户:id
粉丝:user_id,follower_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();
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
任何帮助表示赞赏:)
vFr*_*sop 38
我相信你的加入错了:
$shares = DB::table('shares')
->join('users', 'users.id', '=', 'shares.user_id')
->join('followers', 'followers.user_id', '=', 'users.id')
->where('followers.follower_id', '=', 3)
->get();
Run Code Online (Sandbox Code Playgroud)
我也建议您命名表作为follows代替,感觉更自然一点说user has many followers through follows和user has many followees through follows.
例
$shares = DB::table('shares')
->join('users', 'users.id', '=', 'shares.user_id')
->join('follows', 'follows.user_id', '=', 'users.id')
->where('follows.follower_id', '=', 3)
->get();
Run Code Online (Sandbox Code Playgroud)
我没有意识到你使用的是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');
}
}
Run Code Online (Sandbox Code Playgroud)
模型用法示例:
$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;
Run Code Online (Sandbox Code Playgroud)