【问题标题】:phpactiverecord: get objects related by conditionphpactiverecord:按条件获取对象
【发布时间】:2012-12-26 13:22:15
【问题描述】:

我正在使用ActiveRecord,而数据库已经存在。 我需要获取与 account_type = 'A' 的人相关的所有帐户,所以我有:

class Person extends ActiveRecord\Model {

static $has_many = array(
    array(
        'accounts',
        'conditions' => array('account_type = ?' => array('A')),
        'class_name' => 'Accounts',
        'foreign_key' => 'idpersona'
    )
);

但我收到错误 No bound parameter for index 3。我试图删除行 'conditions' => array('account_type = ?' => array('A')) 并且该应用程序运行正常。我做错了什么?

【问题讨论】:

    标签: php database activerecord phpactiverecord


    【解决方案1】:

    “语法”不同,条件应该是一个数组 array('account_type = ?', 'A')

    【讨论】:

      【解决方案2】:

      以下应该有效。请注意将 array('A') 更改为简单的 'A'。

      class Person extends ActiveRecord\Model {
      
      static $has_many = array(
          array(
              'accounts',
              'conditions' => array('account_type = ?' => 'A'),
              'class_name' => 'Accounts',
              'foreign_key' => 'idpersona'
          )
      );
      

      如果您的查询需要一系列输入或者您有多个要替换的标记,您只需要数组中的值。

      在此处查看示例:http://www.phpactiverecord.org/projects/main/wiki/Finders#conditions

      【讨论】:

        【解决方案3】:

        我自己的解决方案:

        class Person extends ActiveRecord\Model {
        
        static $has_many = array(
            array(
                'accounts',
                'conditions' => "account_type = 'A'",
                'class_name' => 'Accounts',
                'foreign_key' => 'idpersona'
            )
        );
        

        【讨论】:

        • 在这种特殊情况下,这可以正常工作,因为“A”是文字,而不是用户提供的变量。使用数组而不是字符串只是一个好习惯,因为 activerecord 会自动阻止 sql 注入
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-02
        • 2010-09-20
        • 2011-01-02
        • 1970-01-01
        • 2013-10-29
        相关资源
        最近更新 更多