Reputation: 714
I have two tables country
and user
.
In model country
I have relation:
'users' => array(self::HAS_MANY, 'User', 'country_id')
I want to find all the countries which have at least one user. If there are no users from Germany, Germany will be excluded from the result.
Tried this one:
$criteria = new CDbCriteria();
$criteria->join = 'INNER JOIN user ON country.id = user.country_id';
$criteria->order = 'name ASC';
$countries = country::model()->findAll($criteria);
But in the result I had all the countries.
Any suggestions?
Upvotes: 1
Views: 806
Reputation: 2656
$criteria = new CDbCriteria();
$criteria->with = array('users');
$criteria->addCondition('users.id IS NOT NULL');
$countries = Country::model()->findAll($criteria);
or
$countries = Country::model()->with('users')->findAll('users.id IS NOT NULL');
Note that I assumed that the primary key in the users
table is id
. Change it to whatever it is in your case.
Upvotes: 3