【发布时间】:2018-09-27 03:41:06
【问题描述】:
我有一个多对多的关系,如下所示。用户可以更改他们的角色,我希望所有用户的最后一个角色等于角色 2(示例)。
用户
user_id | user_name | user_password
1 | user1 | *hashed password*
2 | user2 | *hashed password*
3 | user3 | *hashed password*
角色
role_id | role_name | role_description
1 | role1 | *description*
2 | role2 | *description*
用户角色
user_roles_id | user_id | role_id | created_at
1 | 1 | 1 | 2018-04-10 01:01:01
2 | 2 | 2 | 2018-04-10 01:01:02
3 | 3 | 1 | 2018-04-10 01:01:03
4 | 1 | 2 | 2018-04-12 01:01:01
5 | 1 | 1 | 2018-04-13 01:01:02
6 | 2 | 1 | 2018-04-14 01:01:01
7 | 3 | 2 | 2018-04-14 01:01:02
8 | 2 | 2 | 2018-04-15 01:01:01
9 | 1 | 2 | 2018-04-15 01:01:02
10 | 1 | 1 | 2018-04-16 01:01:01
从这些表中,我想得到类似的东西
user_id | role_id
2 | 2
3 | 2
但一直以来我都得到了
user_id | role_id
1 | 2
2 | 2
3 | 2
user1 不应该在那里,因为它的最后一个角色是role1。
所以我想做的是,让用户最后一个角色= 2。
任何帮助将不胜感激!提前致谢!
加法
我想要的结果是来自users 表的所有数据。所以可能是这样的
user_id | user_name | <and all of the rest>
2 | user2 | ...
3 | user3 | ...
所以,我上面提到的字段role_id只是选择用户的参考。
【问题讨论】:
-
为什么不直接选择这样的用户:
SELECT user.user_id, role_id FROM users JOIN user_roles ON user.user_id = user_roles.user_id WHERE role_id = 2 GROUP BY user.user_id, role_id -
很好,但是该查询将包括
user1,我想选择最后一个角色= 2的用户,所以这可能包括created_at字段。提前致谢! -
啊,明白了。
-
也许这会有所帮助?我知道我的数据库,但出于某种原因不擅长编写查询。这看起来很像你需要的东西:stackoverflow.com/questions/2411559/…
-
您使用的是什么关系型数据库?
sql太笼统了。
标签: sql laravel eloquent many-to-many relationship