如何从laravel中的子关系中获取字段?

nwo49xxi  于 2021-06-15  发布在  Mysql
关注(0)|答案(1)|浏览(266)

目标:
包括 category_name 字段输入 $posts 属性。相应的fk- category_id 目前已包含在我的报税表中。
控制器返回所有 Posts 用他们的 PostChild s return $posts = Post::with('postchildren')->get(); post model有很多post child

public function postchildren() {
    $this->hasMany('App\PostChild')
}

后儿童模型有一个类别
(此表有一个 category_id 字段的fk idCategory 型号。)

public function category() {
    $this->hasOne('App\Category');
 }

类别模型
这张table有一张table category_name 领域

3qpi33ja

3qpi33ja1#

你应该能够通过hasmanythrough关系获得与孩子们相关的所有类别。

class Post
{
    public function categories()
    {
        return $this->hasManyThrough(PostChild::class, Category::class);
    }
}

然后您可以直接访问post对象上的类别。

$categories = Post::first()->categories;

或者如果你想要一个类似的数组

$posts = Post::with('categories')->get();

如果你一直想要 categories 加载到可以定义的post类上

class Post
{
    protected $with = ['categories'];

相关问题