Laravel加入3桌

Laravel加入3桌,第1张

Laravel加入3桌

我相信您的加入是错误的:

$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;


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5150203.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存