我有以下Phql查询:
$persons = Person::query()
->columns([
'id' => 'id',
'name' => 'first_name || last_name'
])
->where("first_name LIKE :searchQuery:")
->orWhere("last_name LIKE :searchQuery:")
->bind(['searchQuery' => $searchQuery . '%'])
->execute();
使用的数据库是 sqlite 数据库。
查询正常工作,直到我包含 sqlite ||
的连接运算符
抛出的异常是:
扫描仪:未知的操作码402
我尝试了CONCAT(first_name, last_name)
,但它抛出异常:
SQLSTATE [HY000]:一般错误:1没有这样的功能:CONCAT
答案 0 :(得分:2)
使用方言扩展也更好:
namespace App/Dialect;
class Sqlite extends \Phalcon\Db\Dialect\Sqlite
{
/**
* Sqlite constructor.
*/
public function __construct()
{
$this->registerCustomFunctions();
}
/**
* Register Custom dialect functions
*/
public function registerCustomFunctions()
{
$customFunctions = [
'CONCAT_WS' => 'ConcatWs',
];
foreach ($customFunctions as $key => $value) {
$className = 'App\\Dialect\\Extensions\\'.$value;
$object = new $className;
$this->registerCustomFunction($key, $object->getFunction());
}
}
}
namespace App/Dialect/Extensions;
class ConcatWs
{
public function getFunction()
{
return function (Dialect $dialect, $expression) {
$sql = '';
$count = count($expression['arguments']);
if (true !== $count >= 2) {
throw new Exception('CONCAT_WS requires 2 or more parameters');
}
if (2 === $count) {
return $this->getSqlExpression($expression['arguments'][1]);
}
$separator = array_shift($expression['arguments']);
--$count;
foreach ($expression['arguments'] as $argument) {
$sql .= $this->getSqlExpression($argument);
if (0 !== --$count) {
$sql .= ' || '.$this->getSqlExpression($separator).' || ';
}
}
return $sql;
};
}
}
然后在您的数据库服务中:
use App/Dialect/Sqlite as SqliteDialect;
$di->set('db', function() {
return new Sqlite([
// other options, like password etc
'dialectClass' => SqliteDialect::class
]);
});
答案 1 :(得分:0)
遗憾的是,sqllite不支持此功能,但您可以扩展该类并添加对MySQL concat功能的支持。这是一个有效的解决方案:https://forum.phalconphp.com/discussion/15233/concatenate-columns-using-sqlite
MySQL解决方案:
->columns([
'id',
'CONCAT_WS("@", id, created_at) AS concatenatedValue',
])
结果
Array
(
[0] => Array
(
[id] => 1
[concatenatedValue] => 1@2017-04-04 12:08:52