【问题标题】:"NOT IN" Kohana ORM“不在”Kohana ORM
【发布时间】:2012-10-25 16:38:19
【问题描述】:

我有以下型号:

class Model_User extends ORM {

    protected $_primary_key = 'name';

    protected $_has_many = array(
        'repositories' => array(
            'model' => 'repository',
            'through' => 'repository_user',
        ),
    );
}

class Model_Repository extends ORM {

    protected $_primary_key = 'name';

    protected $_has_many = array(
        'users' => array(
            'model' => 'user',
            'through' => 'repository_user',
        ),
    );
}

我使用以下代码获取所有未连接到存储库的用户:

$repository = ORM::factory( 'repository', $this->request->param('svn_name') );
$users = ORM::factory('user')->where( 'name', 'NOT IN', $repository->users->find_all()->as_array() )
            ->find_all();

很遗憾,如果没有用户连接到特定存储库,我会收到以下错误消息:

Database_Exception [ 1064 ]: You have an error in your SQL syntax; check the manual
 that corresponds to your MySQL server version for the right syntax to use near     
')' at line 1 [ SELECT `user`.* FROM `users` AS `user` WHERE `name` NOT IN () ]

如何在不使用 if 且仅使用 Kohana-Methods 的情况下解决此问题?

【问题讨论】:

    标签: php orm kohana kohana-orm kohana-3.2


    【解决方案1】:

    问题在于 $repository->users->find_all()->as_array() 返回一个空数组,因此您的 SQL 查询无效(NOT IN () -> 语法无效)。
    您应该在应用 where 条件之前检查数组是否为空:

    $repository = ORM::factory( 'repository', $this->request->param('svn_name') );
    $names = $repository->users->find_all()->as_array();
    $users = ORM::factory('user');
    
    // Check against empty names
    if (!empty($names))
    {
       $users->where( 'name', 'NOT IN', $names );
    }
    
    // Execute the query
    $users->find_all();
    

    【讨论】:

      猜你喜欢
      • 2012-12-11
      • 2011-10-23
      • 2012-11-17
      • 1970-01-01
      • 2012-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多