laravel - “方法”与 Laravel 在 Eloquent ORM 中的 'Dynamic Property' 对比?

标签 laravel laravel-4 eloquent

我想计算属于标签的帖子数。我应该使用方法还是动态属性?

<?php

class Tag extends Eloquent {

    public function posts()
    {
        return $this->belongsToMany('Post');
    }

    public function postsCount()
    {
        return count($this->posts);
    }

    public function getPostsCountAttribute()
    {
        return count($this->posts);
    }

}

所以在模板中我应该使用动态属性:

{{ $tag->postCount }}

或方法:

{{ $tag->postCount() }}

最佳答案

Laravel 4 文档中有关 Eloquent 的 Dynamic Properties 的摘录关系中的(访问者)(粗体是我的):

Eloquent allows you to access your relations via dynamic properties. Eloquent will automatically load the relationship for you, and is even smart enough to know whether to call the get (for one-to-many relationships) or first (for one-to-one relationships) method. It will then be accessible via a dynamic property by the same name as the relation.

也就是说,使用为数据库关系或动态属性(访问器)定义的方法会有不同的行为。

如果您使用以下方法发布帖子计数:

$count = $tag->posts()->count();

这将使用 COUNT 聚合函数生成正确的 SQL。

另一方面,如果您使用动态属性(访问器)发布帖子计数,如下所示:

$count = count($tag->posts);

这将获取所有帖子,将它们转换为对象数组,然后计算数组元素的数量。

在您的情况下,选择应取决于与标签相关的帖子的使用情况。如果只想统计,那就用方法和聚合函数。但是,如果除了计数之外,您还要对这些帖子执行其他操作,那么请使用动态属性(访问器)。

关于laravel - “方法”与 Laravel 在 Eloquent ORM 中的 'Dynamic Property' 对比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17974806/

相关文章:

php - Codeigniter/Eloquent 选择但不插入

laravel - dd() 在 vue-laravel 项目 axios 调用中不起作用。是否可以在 axios 调用中使用转储?

php - 如何在 Laravel 5.1 中使用 Github、Facebook、Gmail 和 Twitter 登录?

html - Laravel blade模板中的图片路径问题

php - Laravel日期未插入数据库表中

php - 使用 Codeception 和 Laravel 进行登录测试

php - MVC(Laravel)在哪里添加逻辑

php - 如何编写包含精选 MySQL 用户定义变量的 Laravel 连接

php - Laravel 不会让我迁移表,因为它已经存在

php - Laravel Eloquent 问题获取数据库数据