【问题标题】:CakePHP 3 - Easiest way to retrieve a single field from the databaseCakePHP 3 - 从数据库中检索单个字段的最简单方法
【发布时间】:2016-04-18 18:04:02
【问题描述】:

在 CakePHP 2 中我可以这样做:

$name = $this->User->field('name', ['email' => 'user@example.com']);

在 CakePHP 3 中,你必须这样做才能达到同样的效果:

$users = TableRegistry::get('Users');

$query = $users->find()
    ->select('name')
    ->where(['email' => 'user@example.com']);

$name = $query->isEmpty() ? null : $query->first()->name;

有没有更简单的方法来执行这些操作?我对新的 ORM 不是很熟悉。


编辑:我添加了一个为 Cake 3 添加此行为的类示例:

https://stackoverflow.com/a/42136955/851885

【问题讨论】:

    标签: cakephp cakephp-3.0


    【解决方案1】:

    可以通过自定义行为将此功能添加到任何表格。

    另存为src/Model/Behavior/EnhancedFinderBehavior.php


    <?php
    namespace App\Model\Behavior;
    
    use Cake\ORM\Behavior;
    
    /**
     * EnhancedFinder behavior
     * 
     * Behavior providing additional methods for retrieving data.
     */
    class EnhancedFinderBehavior extends Behavior
    {
    
        /**
         * Retrieve a single field value
         * 
         * @param  string $fieldName The name of the table field to retrieve.
         * @param  array $conditions An array of conditions for the find.
         * @return mixed The value of the specified field from the first row of the result set.
         */
        public function field($fieldName, array $conditions)
        {
            $field = $this->_table->getAlias() . '.' . $fieldName;
            $query = $this->_table->find()->select($field)->where($conditions);
    
            if ($query->isEmpty()) {
                return null;
            }
            return $query->first()->{$fieldName};
        }
    }
    

    注意:对于 3.4 之前的 CakePHP 版本,将代码更改为 $this-&gt;_table-&gt;alias(),在以后的版本中已弃用 getAlias()


    用法

    将行为添加到您的类中:

    <?php
    namespace App\Model\Table;
    
    use Cake\ORM\Table;
    
    class UsersTable extends Table
    {
    
        public function initialize(array $config)
        {
            $this->addBehavior('EnhancedFinder');
        }
    }
    

    现在你可以像 Cake 2 一样使用查找器了:

    $name = $this->User->field('name', ['id' => 1]);
    

    【讨论】:

    • 现在 alias 方法已被弃用。更新代码最接近的方法是什么?
    • @Mark 较新的方法是getAlias()。我更新了我的答案。
    【解决方案2】:

    这可能比你的简单

    $users = TableRegistry::get('Users');
    $name = $users->get(1)->name;
    

    确保在使用get函数时,参数应该是表中的主键。

    【讨论】:

    • 这个方法的查询对象不是选择所有字段吗,也就是说获取一个字段可能会从表中选择100个字段?
    • @BadHorsie 是的。它获取所有字段。如果您想选择一个字段以获得更好的性能,那么您应该使用 find 方法来选择该字段。
    • @Eric Lee,谢谢。你节省了我的时间。
    • 使用这种方法来检索一个字段是没有意义的。 $users-&gt;get(1) 已经完成了所有“艰苦的工作”,您要求将它已经拥有的 100 个字段中的一个字段值传递给您。
    • 此方法也只能用于通过ID检索记录,不能选择任何单个字段。
    【解决方案3】:

    不,CakePHP 3.x 中没有。

    如果您希望该方法在行为中或作为查找器使用 trait 并将其与您的表对象一起使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 2019-08-30
      • 2013-12-20
      • 2016-04-05
      • 2015-08-17
      相关资源
      最近更新 更多