【问题标题】:PHP Activerecord; pass in associative array as conditionsPHP 活动记录;传入关联数组作为条件
【发布时间】:2014-07-20 11:22:59
【问题描述】:

我知道在 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 中是否可行,而且 - 它是安全/可靠的操作吗?

【问题讨论】:

    标签: php activerecord


    【解决方案1】:

    我写这个是为了确保行为一致。语法是:

    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 有更好的或内部的方法来做到这一点,请告诉我,我仍然会选择你的答案。

    【讨论】:

      猜你喜欢
      • 2016-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多