Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii Criteria: condition for relation

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 = ????
like image 355
Taram Avatar asked Mar 11 '14 08:03

Taram


2 Answers

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)
like image 119
Taram Avatar answered Sep 22 '22 11:09

Taram


$criteria = new CDbCriteria();
$criteria->with = array('works');
$criteria->compare('works.theField_name' , $someThing);
like image 39
Developerium Avatar answered Sep 25 '22 11:09

Developerium