Laravel中的多重关系(枢轴)

问题描述 投票:2回答:1

我有相关模型的问题。

有三种型号。用户,PostType(音乐,动物)和帖子。

用户可以选择他想要看的后期类型。所以我创建了一个pivot-table posttype_user。现在我可以将选定的postTypes保存到用户。

// User model
    public function postTypes()
    {
        return $this->belongsToMany(PostType::class);
    }

// PostType model
    public function users()
    {
        return $this->belongsToMany(User::class);
    }

Post模型有一个带有postType_id的外键。这种关系在模型中:

// Post model
    public function postType()
    {
        return $this->belongsTo(PostType::class);
    }

// PostType model
    public function post()
    {
       return $this->hasMany(Post::class);
    }

现在我想从当前用户(Auth :: user())接收所有Posts(选定的posTypes)。

但我不知道怎么做。有没有人有想法?

php laravel pivot
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.