在 yii 中使用 CActiveDataProvider 获取数据
我有 3 个表,标准关系多对多 用户(id,...)-> Users_Has_Courses(Users_id, Courses_id) ->; Courses(id,...)
课程模型有下一个关系
'users' => array(self::MANY_MANY, 'Users', 'users_has_courses(Courses_id, Users_id)')
用户模型有下一个关系
'courses' => array(self::MANY_MANY, 'Courses', 'users_has_courses(Users_id, Courses_id)')
请说明我如何获取课程列表,其中指定“id”的用户尚未通过 CActiveDataProvider 订阅? 换句话说,我需要这个简单 SQL 查询的类似物,
select * from Courses where id not in (select Courses_id from users_has_courses where Users_id = 2)
感谢您的帮助
I have 3 tables, standart relation MANY-TO-MANY
Users(id,...) -> Users_Has_Courses(Users_id, Courses_id) -> Courses(id,...)
Courses Model has next relation
'users' => array(self::MANY_MANY, 'Users', 'users_has_courses(Courses_id, Users_id)')
Users Model has next relation
'courses' => array(self::MANY_MANY, 'Courses', 'users_has_courses(Users_id, Courses_id)')
Please, say how I can get list of courses, on which user with specified "id" hasn't been subscribed with CActiveDataProvider ?
Otherwords, I need an analogue of this plain SQL query
select * from Courses where id not in (select Courses_id from users_has_courses where Users_id = 2)
thanks for the help
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用参数化的命名范围来封装查询,而不是常规的“关系”。在您的课程模型中,添加此范围函数以获取用户不在其中的所有课程的列表:
然后您应该能够执行以下操作:
该代码完全未经测试,但原则上应该可以工作。当我有一个复杂的查询时,我经常做这种事情,但我仍然想使用 AR 功能,比如 CActiveDataProvider。在此处阅读有关“命名范围”的更多信息:
http: //www.yiiframework.com/doc/guide/1.1/en/database.ar#parameterized-named-scopes
祝你好运!
Instead of a regular "relation", try a parametrized Named Scope to encapsulate the query. In your Courses model, add this scope function to get a list of all the courses the user is not in:
Then you should be able to do this:
This code is completely untested, but it should work in principle. I do this sort of thing often when I have a complex query but I still want to use the AR features, like CActiveDataProvider. Read more about "named scopes" here:
http://www.yiiframework.com/doc/guide/1.1/en/database.ar#parameterized-named-scopes
Good luck!