【问题标题】:Laravel 5.1: Get only the records of the related modelLaravel 5.1:只获取相关模型的记录
【发布时间】:2017-02-16 12:03:46
【问题描述】:

我有三个模型:

  • 类别
  • 发布
  • 评论

这些是它们的实现:

class Category extends \Eloquent {
    public function posts() {
        return $this->hasMany('Post');
    }
}


class Post extends \Eloquent {
    public function category() {
        return $this->belongsTo('Category');
    }
    public function comments() {
        return $this->hasMany('Comment');
    }
}

class Comment extends \Eloquent {
    public function post() {
        return $this->belongsTo('Post');
    }
}

是否有可能使用 eloquent 获取与某个类别相关的所有 cmets(并且只有 cmets,没有帖子)的列表(数组或集合)? (这意味着,给定一个类别,找到所有相关的帖子,然后返回所有相关的 cmets)。

提前致谢!

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    只需在您的模型类别上使用hasManyThrough 关系:

    class Category extends \Eloquent {
        public function posts() {
            return $this->hasMany(Post::class);
        }
        public function comments() {
            return $this->hasManyThrough(Comment:class,Post::class);
        }
    }
    

    之后,您可以简单地调用$category->comments 来获得一个包含与某个类别相关的所有 cmets 的集合。

    更多信息请参见https://laravel.com/docs/5.1/eloquent-relationships#has-many-through

    对于 Laravel 5.3:https://laravel.com/docs/5.3/eloquent-relationships#has-many-through

    【讨论】:

    • 谢谢!我以完全不同的方式做这件事,但 hasManyThrough 完全符合我的需要。非常感谢
    猜你喜欢
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 2019-02-24
    • 2022-01-12
    • 2021-09-28
    • 1970-01-01
    相关资源
    最近更新 更多