我正在构建类似Twitter的应用程序。有一个供稿,我只想在其中显示我关注的用户的帖子。
我尝试了所有使用join的操作,但是似乎没有任何效果。
我有3个表:Users,Followers,Shares
Users
Followers
Shares
表格如下所示:
用户数 :id
id
关注 :user_id,follower_id
user_id
follower_id
股份 :user_id
我需要得到的是“所有共享,其中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 follows和user has many followees through follows。
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();
我没有意识到您正在使用DB::查询而不是模型。因此,我正在解决问题并提供更多的清晰度。我建议您使用模型,对于那些从框架(尤其是SQL)开始的人来说,它要容易得多。
DB::
型号示例:
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;