如何在 Laravel 中连接三个表以获得类似 Twitter 的 Feed?

DDD
发布: 2024-10-27 00:00:05
原创
754 人浏览过

How to Join Three Tables in Laravel for a Twitter-like Feed?

Laravel 连接 3 个表

要连接 Laravel 中的三个表以获得类似 Twitter 的提要,连接查询可以构建如下:

$shares = DB::table('shares')
    ->join('users', 'users.id', '=', 'shares.user_id')
    ->join('followers', 'followers.user_id', '=', 'users.id')
    ->where('followers.follower_id', '=', 3)
    ->get();
登录后复制

此查询根据联接子句中指定的条件联接份额、用户和关注者表。

另一种方法是使用模型而不是原始查询来获得更多信息面向对象的方法。以下是使用模型的示例:

// Define User Model
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');
    }
}

// Define Share Model
class Share extends Model {
    public function user() {
        return $this->belongsTo('User');
    }
}

// Model Usage
$my = User::find('my_id');

$shares = Share::with('user')
    ->join('follows', 'follows.user_id', '=', 'shares.user_id')
    ->where('follows.follower_id', '=', $my->id)
    ->get('shares.*');

foreach ($shares as $share) {
    echo $share->user->username;
}
登录后复制

通过使用此模型方法,您可以检索登录用户关注的用户的所有共享,并立即加载创建共享的用户。

以上是如何在 Laravel 中连接三个表以获得类似 Twitter 的 Feed?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!