检索关系记录 laravel

Retrieve records on relationship laravel

我需要在用户登录时显示主题中已发布的帖子。用户可以关注多个主题。 1 个主题有很多帖子,1 个主题有很多用户 'enrolled' 通过数据透视表 table 'topic_user'

我想知道对此的查询..

我有这 4 个模型:

1 - 正常 用户

然后:

class Post extends Model
{
    use SoftDeletes;
    //
    protected $fillable = ['title','content', 'creator_id','topic_id','flag_id','deleted_at',"created_at"];
    
    public function topic(){
        return $this->belongsTo(Topic::class);
    }
}
class Topic extends Model
{
    use SoftDeletes;
    protected $fillable = ['name','description','active','creator_id','nsfw','type_id','formal_name','theme','joined_community'];

    public function posts(){
        return $this->hasMany(Post::class);
    }
    public function enrolled(){
        return $this->belongsToMany(User::class,'topic_user');
    }
}
class UserOnTopic extends Model
{
    protected $fillable = ["user_id","topic_id"];
    protected $table = "topic_user";
}

您已经建立了您的关系。因此,您可以使用主题和帖子查询用户:

$user_posts = User::with('topics', 'topics.posts')->first();

这行代码 returns 第一个用户,以及属于他关注的主题的所有帖子。

您可以使用如下方式在您的前端显示他的帖子:

<ul>
@foreach($user_posts->topics as $topic)
    @foreach($topic->posts as $post)
        <li>{{ $post->id }}</li>
    @endforeach
@endforeach
</ul>