i have two tables: User and User_works (User HAS_MANY User_works).
How can I add a condition to be displayed only users with certain works
User contains fields: id | name | Other information
User_works: id | user_id | work_id
User Model:
public function relations()
{
return array(
'works'=>array(self::HAS_MANY, 'UserWorks',
'',
'on' => 'works.user_id=t.id',
'together'=>false,
),
)
}
Controller:
$criteria = new CDbCriteria();
$criteria->with = array('works');
$criteria->compare = ????
Solution:
I wanted something like that:
SQL "Select user.id from User, User_works Where User_works.user_id=User.id AND User_works.work_id=$SOMEVALUE"
User Model:
public function relations()
{
return array(
'works'=>array(self::HAS_MANY, 'UserWorks',
'',
'joinType' => 'INNER JOIN',
'on' => 'works.user_id=t.id',
'together'=>true,
),
)
}
Controller:
$criteria = new CDbCriteria();
$criteria->with = array('works'=>array('on' => 'works.user_id=t.id AND (works.work_id=$SOMEVALUE OR ...)'));
As a result, I get the users with the necessary works.
But а new problem arose. The number of pages in the Listview not correctly displays. List view does not consider the condition of necessary works. As a result, a number of page is wrong.
Solution :
$dataProvider=new CActiveDataProvider('User', array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>1,
),
));
$dataProvider->setTotalItemCount(count(User::Model()($criteria)));
or
Instead of setting the dataprovider criteria:
$dataProvider->criteria = $criteria
I set dataprovider->model criteria:
$dataProvider->model->setDbCriteria($criteria)