当 :has_and_belongst_to_many 时,在 Rails 中嵌套 sql 查询
在我的应用程序中,我执行用户尚未完成的下一个任务。我有三个模型,一本有许多任务的书,然后我有一个拥有并属于许多任务的用户。表task_users 表包含所有已完成的任务,因此我需要编写一个复杂的查询来查找下一个要执行的任务。
我在纯 SQL 中提出了两个可行的解决方案,但我无法将它们转换为 Rails,这就是我需要的帮助
SELECT * FROM `tasks`
WHERE `tasks`.`book_id` = @book_id
AND `tasks`.`id` NOT IN (
SELECT `tasks_users`.`task_id`
FROM `tasks_users`
WHERE `tasks_users`.`user_id` = @user_id)
ORDER BY `task`.`date` ASC
LIMIT 1;
,同样没有嵌套选择
SELECT *
FROM tasks
LEFT JOIN tasks_users
ON tasks_users.tasks_id = task.id
AND tasks_users.user_id = @user_id
WHERE tasks_users.task_id IS NULL
AND tasks.book_id = @book_id
LIMIT 1;
这是我使用 MetaWhere 插件在 Rails 中所做的,
book.tasks.joins(:users.outer).where(:users => {:id => nil})
但我不知道如何也让当前用户也到达那里,
感谢您的帮助!
In my application I the next task that has not already been done by a user. I have Three models, A Book that has many Tasks and then I have a User that has has and belongs to many tasks. The table tasks_users table contains all completed tasks so I need to write a complex query to find the next task to perform.
I have came up with two solutions in pure SQL that works, but I cant translate them to rails, thats what I need help with
SELECT * FROM `tasks`
WHERE `tasks`.`book_id` = @book_id
AND `tasks`.`id` NOT IN (
SELECT `tasks_users`.`task_id`
FROM `tasks_users`
WHERE `tasks_users`.`user_id` = @user_id)
ORDER BY `task`.`date` ASC
LIMIT 1;
and equally without nested select
SELECT *
FROM tasks
LEFT JOIN tasks_users
ON tasks_users.tasks_id = task.id
AND tasks_users.user_id = @user_id
WHERE tasks_users.task_id IS NULL
AND tasks.book_id = @book_id
LIMIT 1;
This is what I Have done in rails with the MetaWhere plugin
book.tasks.joins(:users.outer).where(:users => {:id => nil})
but I cant figure out how to get the current user there too,
Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这将使用 LEFT JOIN 重复第二种形式:
请注意,它使用表名
task_user
而不是tasks_users
,这对于连接模型来说更为典型。另外,它需要通过以下方式调用:I think this will duplicate the second form with the LEFT JOIN:
Note that instead of
tasks_users
this uses the table nametask_user
, which is more typical for a join model. Also, it needs to be called with:这将为您提供第一个任务,该任务在当前用户的tasks_users 中还没有条目。
That would give you the first task that doesn't already have an entry in tasks_users for the current user.