我正在构建一个类似Twitter的应用程序。这里有一个Feed,我只想显示我跟踪的用户的帖子。
我什么都试过了,但似乎什么都没有用。
我有三张桌子:Users
,Followers
,Shares
这些桌子看起来如下:
用户:id
追随者:user_id
,follower_id
股票:user_id
我需要得到的是“share.user_id =followers.follower_id的所有股票”和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();
但它不起作用。
如有任何帮助,我们将不胜感激:)
发布于 2013-08-22 19:20:41
我相信你的加入是错误的:
$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
会更自然一些。
示例
$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;
发布于 2013-08-22 20:18:10
就一般的MySQL语法而言,最好编写如下:
SELECT * FROM USER a JOIN FOLLOWERS b ON (a.id = b.user_id) JOIN SHARES c on (b.follower_id = c.user_id) WHERE a.id = 3
将返回所有追随者及其各自份额的数据集。
我相信你会想要在拉勒维尔
DB::table('USER')
->join('FOLLOWERS', 'USER.id', '=', 'FOLLOWERS.user_id')
->join('SHARES', 'FOLLOWERS.follower_id', '=', 'SHARES.user_id')
->where('USER.id', 3)
->get();
发布于 2017-05-25 20:29:13
而不是
->where('shares.user_id', 'followers.follower_id')
它应该是
->whereRaw('shares.user_id=followers.follower_id')
因为在最初的示例中,“followers.follower_id”被解释为字符串。
https://stackoverflow.com/questions/18388664
复制相似问题