在CakePHP 2中,我可以执行以下操作:
$name = $this->User->field('name', ['email' => '[email protected]']);
在CakePHP 3中,您必须执行以下操作才能实现相同的目的:
$users = TableRegistry::get('Users');
$query = $users->find()
->select('name')
->where(['email' => '[email protected]']);
$name = $query->isEmpty() ? null : $query->first()->name;
有没有更简单的方法来执行此类操作?我对新的ORM不太熟悉。
编辑:我添加了一个类的示例,该类为Cake 3添加了此行为:
可以通过自定义行为将此功能添加到任何表中。
另存为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->_table->alias()
,不建议使用,以支持getAlias()
更高版本。
用法
将行为添加到您的班级:
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class UsersTable extends Table
{
public function initialize(array $config)
{
$this->addBehavior('EnhancedFinder');
}
}
现在,您可以像蛋糕2一样使用查找器:
$name = $this->User->field('name', ['id' => 1]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句