1

我有以下型号:

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 方法的情况下解决此问题?

4

1 回答 1

2

问题是$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-10-26T08:44:39.960 回答