我正在尝试将Phalcon \ Mvc \ Model \ Query \ Builder对象与Phalcon \ Mvc \ Model :: find()方法一起使用来自定义数据加载行为。
表中的所有模型行都有“record_status”字段,用于标记活动/非活动记录。
我打算扩展Model :: find()和Model :: findFirst()方法,以便始终将“record_status = 1”约束添加到我的所有Model查询中。但是现在,我只是想在外部将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)会从数据库中返回所有行,而忽略将WHERE子句设置为$ query。
检查$ 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
答案 0 :(得分:2)
你有错误。
Model::find()
和Model::findFirst()
函数接受数组,int或字符串,并且是查询构建器的包装器。
您至少有两个选择:
a)直接使用查询构建器:
// ... here is your query builder script as in question
$results = $query->getQuery()->execute();
$firstFound = $results->getFirst();
b)将数组传递给Model::findFirst()
:
$firstFound = User::findFirst(
array(
'(email = :email:) AND (record_status = :status:)',
'bind' => array('email' => 'root@yahoo.com', 'status' => 1)
)
);