1

我正在尝试将 Phalcon\Mvc\Model\Query\Builder 对象与 Phalcon\Mvc\Model::find() 方法一起使用来自定义数据加载行为。

表中的所有模型行都有“record_status”字段,用于标记记录活动/非活动。

我打算扩展 Model::find() 和 Model::findFirst() 方法以始终将“record_status=1”约束添加到我的所有模型查询中。但就目前而言,我只是试图将 Query\Builder 对象从外部传递给 ::find() 方法:

class User extends Phalcon\Mvc\Model
{
}

$user = new User();

/**
 * @var Phalcon\Mvc\Model\Query\Builder
 */
$query = $user->getModelsManager()->createBuilder();

$query->where('email = :email:', [
    'email' => 'root@yahoo.com'
])->andWhere('record_status = :status:', [
    'status' => 1
])->from('users');

$found = $user->find($query);

foreach ($found as $foundUser) {
    ...
}

问题是->find($query)从数据库返回所有行,忽略设置为 $query 的 WHERE 子句。

检查 $query 和 $user 的属性时,我看到以下相关的受保护属性:

$query::_conditions = '(email = :email:) AND (record_status = :status:)';
$query::_bindParams = array(
    'email' => 'root@yahoo.com',
    'status' => 1
);

$user::_count = 4; // This is wrong, this corresponds to TOTAL number of rows
$user::_result->_bindParams = NULL; // Bound parameters have disappeared
$user::_result->_sqlStatement = 'SELECT `users`.`id`,  `users`.`email`, `users`.`record_status` FROM `users`'; // As you can see, there is no WHERE clause

我在 Phalcon 1.3.0、PHP 5.5.1 上。

我希望 find() 和 findFirst() 方法接受 Query\Builder() 对象并获取正确的记录。这是一个错误还是我错误地接近它?

谢谢, Temuri

4

1 回答 1

3

Yep you have things wrong.

The Model::find() and Model::findFirst() functions accept arrays, int or string and are wrappers for query builder.

You have at least two options:

a) use query builder directly:

// ... here is your query builder script as in question
$results = $query->getQuery()->execute();
$firstFound = $results->getFirst();

b) pass array to Model::findFirst():

$firstFound = User::findFirst(
    array(
        '(email = :email:) AND (record_status = :status:)',
        'bind' => array('email' => 'root@yahoo.com', 'status' => 1)
   )
);
于 2013-09-23T08:28:34.450 回答