Conditions in model (similar to where clause in SQL)

Need some explanation on this. Having difficulty understanding it.

db table: person (id, first_name, last_name, user_id - fk to user table). relationship, a person can be a user, a user must be a person. Basically a 1 to 1 relationship. Decided to separate for design reasons.

Problem:

I need to list, in a drop down, active users coming from the person table. to populate the dropdown list in a form, i need to write something like:

select first_name, last_name

from person

where user_id is not null

I want to create a method in the person class (model) to make this easy. I wrote something like:

if(user_id != null)

return … first_name, last name…

I though this would return only records where user_id is null. But in reality, it returns the first_name and last_name of all when user_id is null. If not null, it returns the record, but not the first/last name.

Not good. So please explain how i can select/return, in the model, only the records that satisfy a certain condition.

I think you need to embrace active record. Have you read the guide?

Lets assume you have your relations() setup correctly in your Person and User models. Using the AR findAll() method:




$persons=Person::model()->findAll("personId IS NOT NULL")



Please note, if using MySQL you cannot do the following:




$persons=Person::model()->findAll("personId=null")



MySQL requires the use of ‘column IS NOT NULL’ rather than ‘column=null’.

So that gets you your data, but you need to format it for the dropdownlist. I recommend you use the CHtml::listData to do this. Wrap this query inside the listData method and you’ll be there.

thank you dniznick

your where condition worked like charm

regards

charles