我相信您的加入是错误的:
$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和
userhas 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)开始的人来说,它要容易得多。
型号示例:
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 somethingforeach ($shares as $share) { echo $share->user->username;}// Retrieves all users I'm following$my->followees;// Retrieves all users that follows me$my->followers;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)