简体   繁体   English

如何从一个表中获取两个外键值

[英]How to get two foreign key values from one table

I have two tables: 我有两个表:

Users

table.increments('user_id').primary()
table.string('fname').notNull()
table.string('mname').notNull()
table.string('lname').notNull()
table.integer('level_id').notNull()
table.string('username').notNull()
table.string('password').notNull()
table.boolean('is_deleted').defaultTo(false)
table.unique('username')

Messages

table.increments('message_id').primary()
table.integer('sender_id')
table.integer('receiver_id')
table.boolean('is_private').defaultTo(true)
table.text('message')
table.boolean('is_deleted').defaultTo(false)

So now the problem is, I want to join the tables and get the name of the receiver and the sender. 所以现在的问题是,我想联接表并获取接收者和发送者的名称。

At first, I tried to get only the messages and loop the data to gather the receiver and the sender's name, so another query which is very bad so I wanted to get everything in just a single query. 最初,我尝试仅获取消息并循环数据以收集接收方和发送方的名称,因此另一个查询非常糟糕,因此我希望仅通过一个查询就可以获取所有内容。

I tried AND on the JOIN but it resulted to nothing but empty. 我试着在JOIN上执行AND ,但结果空无一物。

SELECT * 
FROM messages m 
JOIN users u ON u.user_id = m.sender_id 
    AND u.user_id = m.receiver_id

To be honest, I am just going round and round, I don't really know the logic behind a query like this. 老实说,我只是一遍又一遍,我真的不知道这样的查询背后的逻辑。

Expected code: 预期的代码:

[
   {  
      "message_id":54,
      "sender_name": 'Ernie Jeash Vill',
      "receiver_name": 'Karma Morningstar Blackshaw',
      "is_private":1,
      "message":"q",
      "is_deleted":0,
      "created_at":"2019-09-03T08:45:09.000Z",
      "updated_at":null,
   },
   {  
      "message_id":53,
      "sender_name":'Karma Morningstar Blackshaw',
      "receiver_name": 'Ernie Jeash Vill',
      "is_private":1,
      "message":"e",
      "is_deleted":0,
      "created_at":"2019-09-03T08:45:09.000Z",
      "updated_at":null,
   }
]

You need to join messages to users twice , one for each name of the receiver and sender: 您需要两次users加入messages ,一次分别针对接收者和发送者的名称:

SELECT
    m.*,
    u1.lname AS sender_last,
    u1.fname AS sender_first,
    u2.lname AS receiver_last,
    u2.fname AS receiver_first
FROM messages m 
INNER JOIN users u1
    ON u1.user_id = m.sender_id
INNER JOIN users u2
    ON u2.user_id = m.receiver_id;

You can have multiple foreign keys from the same table. 同一张表中可以有多个外键。

It does not require any special treatment or syntax. 它不需要任何特殊处理或语法。 Just declare two separate foreign keys on the table. 只需在表上声明两个单独的外键即可。

Read more here: https://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html 在此处阅读更多信息: https : //dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM