CakePHP 3 - 从数据库中检索单个字段的最简单方法

Bad*_*sie 9 cakephp cakephp-3.0

在CakePHP 2中我可以这样做:

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

在CakePHP 3中你必须做这样的事情才能实现同样的目的:

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

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

$name = $query->isEmpty() ? null : $query->first()->name;
Run Code Online (Sandbox Code Playgroud)

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


编辑:我添加了一个类的例子,它为Cake 3添加了这种行为:

/sf/answers/2949586881/

Bad*_*sie 5

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

另存为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->alias() . '.' . $fieldName;
        $query = $this->_table->find()->select($field)->where($conditions);

        if ($query->isEmpty()) {
            return null;
        }
        return $query->first()->{$fieldName};
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

将行为添加到您的班级:

<?php
namespace App\Model\Table;

use Cake\ORM\Table;

class UsersTable extends Table
{

    public function initialize(array $config)
    {
        $this->addBehavior('EnhancedFinder');
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以像蛋糕2一样使用查找器:

$name = $this->User->field('name', ['id' => 1]);
Run Code Online (Sandbox Code Playgroud)