Question

i've got the following models:

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',
        ),
    );
}

I use the following code to get all users which are not connected to a repository:

$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();

Unfortunately i get the following error message if there is no user connected to a specific repository:

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 () ]

How can i solve this problem without using if's and only using Kohana-Methods?

Was it helpful?

Solution

The problem is that $repository->users->find_all()->as_array() returns an empty array so your SQL query is not valid (NOT IN () -> invalid syntax).
You should check if array is empty before applying where condition:

$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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top