表的id由外键的id替换

时间:2017-09-29 07:09:51

标签: react-native sqlite expo

我在反应本机项目中使用Expo的SQLite模块。我有两个表,(消息和用户):

CREATE TABLE IF NOT EXISTS messages (
    id text not null,
    sender_id integer,
    thread_id integer,
    body text,
    foreign key (sender_id) references users (id),
    foreign key (thread_id) references threads (id)
);

CREATE TABLE IF NOT EXISTS users (
    id integer primary key,
    first_name text,
    last_name text,
    email text
);

如果我插入一些消息:

INSERT INTO messages (id, sender_id, thread_id, body) values ('xeieoef-ee, 3, 1, 'test');
INSERT INTO messages (id, sender_id, thread_id, body) values ('ttrefzr-ry, 3, 1, 'payload');

我想通过比较线程ID来获取所有消息,包括其用户的数据。这就是我要查询的方式:

select * from messages, users where thread_id = 2 AND messages.sender_id = users.id;

但是,这会导致消息ID和用户ID相同:

[
    {
      "body": "test",
      "email": "userthree@gmail.com",
      "first_name": "userThreeF",
      "id": 3,
      "last_name": "threeUserL",
      "sender_id": 3,
      "thread_id": 1,
    },
    {
      "body": "payload",
      "email": "userthree@gmail.com",
      "first_name": "userThreeF",
      "id": 3,
      "last_name": "threeUserL",
      "sender_id": 3,
      "thread_id": 1,
    },
]

消息的id不是消息的id,而是拥有自己的id,而id是发送者的id。我在这里做错了什么?

更新代码

我在应用中有一个按钮onpress将数据发送到MessageStore的功能。

sendText = () => {
    const {MessageStore, UserStore, SocketStore} = this.props;
    const data = {
        id: uuid.v4(),
        sender_id: UserStore.userInfo.user.id,
        thread_id: 1,
        body: this.state.text,
    }
    MessageStore.addMessageToDB(data);
}

在商店中,addMessageToDB()将消息添加到数据库,再次调用getMessageFromDatabase()以获取所有消息。

@action addMessageToDB = (payload) => {
    db.transaction(
        tx => {
            tx.executeSql(
                `INSERT INTO messages
                    (id, sender_id, thread_id, body, status) values (?, ?, ?, ?, ?);`,
                [payload.id, payload.sender_id, payload.thread_id, payload.body, "pending"],
                (tx, results) => {
                    console.log('message insertion success')
                },
                (tx, error) => console.log('message insertion error', error)
            );
            this.getMessageFromDatabase(payload.thread_id);
        }
    )
}

@action getMessageFromDatabase = (payload) => {
    console.log('>>> getMessageFromDatabase payload', payload);
    db.transaction(
        tx => {
            tx.executeSql(
                `select * from messages inner join users on messages.sender_id=users.id where thread_id = ?;`, [payload],
                (tx, {rows}) => {
                    console.log('inner join success', rows._array);
                },
                (tx, error) => console.log('inner join error', error),
            );
        }
    )
}

1 个答案:

答案 0 :(得分:0)

使用解决方案进行编辑:

这两个表都有一个' id'列,因此用户ID将覆盖消息ID。

这有效:select messages.*, users.first_name, users.last_name, users.email from messages inner join users on messages.sender_id=users.id where thread_id = ?;