我知道在PHP Activerecord中你可以传入条件数组
// Data Structure
['a=? && b=?', 'foo', 'bar']
// Outputs:
// SELECT * FROM `table` WHERE `a`="foo" && `b`="bar"
但是我在程序的另一部分生成了一个关联数组,我想把它作为直接条件传递进去。列可以变化,所以我不能提前写查询字符串,所以你可以传递一个键/值对的关联数组作为条件使用?我不记得我是否对此有意见。我没有看到任何文档说明标准关联数组是允许的结构。
// Data Structure
['a' =>'foo', 'b' => 'bar']
// Outputs:
// SELECT * FROM `table` WHERE `a`="foo" && `b`="bar"
最后,两种方法之间是否可以混合条件?我还希望将一些条件与键/值对一起传递。
// Data Structure
['(a=? || b=?)', 'foo', 'bar', 'c' => 'baz']
// Outputs:
// SELECT * FROM `table` WHERE (`a`="foo" || `b`="bar") && `c`="baz"
这是可能的在PHP Activerecord,而且-它是一个安全/可靠的操作?
我写这些只是为了确保一致的行为。语法:
mixedConditions($associativeArray, $statement = '', ...$parameters);
使用像…
mixedConditions(['a'=>'foo', 'b'=>'bar'],'`c`=? && `d`=?','baz','qux');
输出一个包含
的数组Array
(
[0] => `a` = ? && `b` = ? && `c`=? && `d`=?
[1] => foo
[2] => bar
[3] => baz
[4] => qux
)
函数:(未经测试)
function mixedConditions ($assoc, $statement = '')
{
$conditions = [];
$statementConditions = array_slice(func_get_args(),2);
foreach ($assoc as $key => $value)
if (is_array($value))
$conditions[] = '`'.preg_replace('#[^a-z0-9'-_]#i','',$key).'` IN (?)';
else
$conditions[] = '`'.preg_replace('#[^a-z0-9'-_]#i','',$key).'` = ?';
if (!empty($statement))
return array_merge([implode(' && ', array_merge($conditions, [$statement]))], array_values($assoc), $statementConditions);
else
return array_merge([implode(' && ', $conditions)], array_values($assoc));
}
注意:函数将从参数名中去掉外来字符。
如果Activerecord有更好的或内部的方法做到这一点,让我知道,我会选择你的答案仍然