Retrieving data using CActiveDataProvider in yii

I have 3 tables, the standard attitude is MANY TO MANY Users (id, ...) → Users_Has_Courses (Users_id, Courses_id) → Courses (id, ...)

Courses Model has the following relationship

'users' => array(self::MANY_MANY, 'Users', 'users_has_courses(Courses_id, Users_id)')

The user model has the following relationship

'courses' => array(self::MANY_MANY, 'Courses', 'users_has_courses(Users_id, Courses_id)')

Tell me, how can I get a list of courses at which the user with the specified "id" has not been subscribed to CActiveDataProvider? Other words, I need an analog of this simple SQL query

select * from Courses where id not in (select Courses_id from users_has_courses where Users_id = 2)

thanks for the help

+3
source share
1 answer

"" Named Scope . "" , , :

public function userNotIn($user_id)
{
  $criteria=new CDbCriteria();
  $criteria->condition .= 't.id NOT IN (SELECT users_has_courses.Courses_id FROM users_has_courses WHERE users_has_courses.Users_id = :userid)';
  $criteria->params[':userid'] = $user_id;
  $this->getDbCriteria()->mergeWith($criteria);
  return $this;
}

:

$coursesNotIn=new CActiveDataProvider(Courses::model()->userNotIn($user->id));

, . , , AR, CActiveDataProvider. " " :

http://www.yiiframework.com/doc/guide/1.1/en/database.ar#parameterized-named-scopes

!

+5

Source: https://habr.com/ru/post/1778754/


All Articles