如何使用CakePHP3 ORM以字符串格式获取where子句?

时间:2015-01-17 05:57:11

标签: php mysql cakephp orm cakephp-3.0

在CakePHP3中,有一个ORM可以帮助构建查询。

documentation,我可以看到

$query = $articles->find(); // build a query that has not run yet
$query->where(['id' => 1]); // Return the same query object

所以在这种情况下,我想要字符串

WHERE `articles`.`id` = 1

经过大量的谷歌搜索后,我发现有一种方式to return just the where clause of a query object

$query->where(['id' => 1])->clause('where'); // Return the where clause in the form of a QueryExpression

更多Google搜索引导我了解如何get the QueryExpression to spit out string representation

$query->where(['id' => 1])->clause('where')->sql($valueBinder); // Return the where clause in string format

这是我的问题。我不知道$ valueBinder应该是什么样子。我不知道如何初始化它。

我也很高兴不使用ValueBinder,只要我可以使用CakePHP 3 ORM以及正确的SQL方言获取字符串格式的where子句。请假设我使用的是MySQL。

请告知。

修改

我尝试将$query->valueBinder()用作$valueBinder

它为空,不包含值c:0的关联1

3 个答案:

答案 0 :(得分:2)

要直接回答您的问题,您可以通过以下方式获取任何子句的SQL:

$binder = new \Cake\ORM\ValueBinder();
$query->clause('where')->sql($binder);

这将使用正确的占位符返回SQL,而不是使用要使用的值。值存在于$binder变量中,用于语句对象。

正如我所看到的,您只想保留where子句的内部结构,以将其传递给另一个请求中的另一个查询。您的解决方案很好,但我想补充一点,您还可以从现有查询中编码完整条件树:

$where = serialize($query->clause('where'));
$anotherQuery->where(unserialize($where)); // A query in another request

在任何情况下,您都需要小心您正在反序列化的内容,因为直接从用户输入中获取它肯定会导致安全问题。

答案 1 :(得分:0)

如果您愿意,可以选择省略此参数。请参阅http://api.cakephp.org/3.0/class-Cake.Database.Query.html#_sql

此外,您可以使用Query成员函数遍历($ visitor,$ parts)来隔离where子句。 $ visitor是一个带有值和子句的函数。您定义$ visitor的行为。 $ parts是一个子句名称数组。我建议将数组(' where')传递给此参数。

答案 2 :(得分:0)

我的解决方法是以json字符串格式存储条件。

使用相同的例子,我所做的是

$data['conditions'] = json_encode(['Articles.id' => 1]); // encode into JSON string
$this->DynamicRules->patchEntity($dynamicRule, $data); // use in edit action of DynamicRulesController

然后当我需要重用这些条件时,我会这样做:

$articlesTable = TableRegistry::get('Articles');
$query = $articlesTable->find(); // new query for Articles

$rule = json_decode($dynamicRule->conditions, true); // get back the conditions in associative array format
$query->where($rule); // re-assign the conditions back

这让我得到了我最终想要的东西。