【发布时间】:2018-03-11 01:10:35
【问题描述】:
我在我的 react native 项目中使用 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。我在这里做错了什么?
更新代码
我在应用程序中有一个按钮,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),
);
}
)
}
【问题讨论】:
-
有趣。我试图在小吃中复制代码,我得到了相同的结果。这是expo link
-
@Kakar 是的!而已。不知道这里出了什么问题。
标签: react-native sqlite expo