这是我的代码
$query = $this->db
->select('*')
->join('users as receiver', 'receiver.user_id = messages.user1')
->join('users as sender', 'sender.user_id = messages.user2')
->get('messages')->result_array();
这是数据库
users table
user_id |username | datetime
1 | abc1 | 000000000
2 | abc2 | 000000000
messages table
msg_id | user1 | user2 | msg | timestamp
1 | 1 | 2 | hello | 000000000
我想获得两个用户的记录作为发送者和接收者。但这次加入给了我最后一次加入的记录。在这种情况下,我得到发件人的记录。 我想要这样的输出
[0] => Array
(
[user1] => stdClass Object
(
[id] => 1
[username] => abc1
[datetime] => 2016-11-07 03:00:00
)
[user2] => stdClass Object
(
[id] => 2
[username] => abc2
[datetime] => 2016-11-07 00:00:00
)
[message] => stdClass Object
(
[id] => 1
[message] => hdf
[timestamp] => 2016-11-06 08:43:26
)
)
提前致谢
答案 0 :(得分:0)
这是用于创建将为您提供两行
的联合查询的SQLselect * from messages m join users u on u.user_id = m.user1 union all select * from messages m join users u on u.user_id = m.user2;
或一行中两个用户的连接语句
select * from messages m join users u1 on u1.user_id = m.user1 join users u2 on u2.user_id = m.user2;