首页 文章

如何通过Eloquent Laravel获得包含我的推文的推文?

提问于
浏览
0

我正在建设像Twitter一样学习Laravel .

我想获取我关注的推文的信息,包括我的推文1个查询 .

这是关系模型 . 请检查,我只收集关于人际关系的信息 .

请给我建议 .

关注Model类Follow extends Model {

Public function user(){
    return $this->belongsTo(User::class, "followed_user_id", "id");
}}

推特模型

class Tweet extends Model {

Public function user(){
    return $this->belongsTo(User::class, "user_id");
}}

用户模型

class User extends Model{

Public function tweet(){
    return $this->hasMany(Tweet::class);
}
Public function followUsers(){
    return $this->hasMany(Follow::class, "follow_user_id");
}
Public function followedUsers(){
    return $this->hasMany(Follow::class, "followed_user_id");
}}

1 回答

  • 0

    如果你想通过他的所有推文获得所有用户,你可以简单地使用

    User::with('tweets')->get();
    

    如果您想在单个查询中获取单个用户的推文,则可以

    User::with(['tweets' => function($query) use ($userId){
    
         $query->where('user_id', $userId);
    
    }])->first()
    

相关问题