栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Laravel加入3桌

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/442626.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号