I am using Expo's SQLite module in my react native project. I have two tables, (messages and users):
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
);
And if I insert some messages:
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');
I would like to get all messages including its user's data by comparing the thread id's. This is how I am querying:
select * from messages, users where thread_id = 2 AND messages.sender_id = users.id;
However, this results in both the message id and user id to be the same:
[
{
"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,
},
]
Instead of message's id to have its own id, the message's id is the sender's id. What am I doing wrong here?
Update code
I have a button in the app which onpress sends the data to the MessageStore's function.
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);
}
On the store, the message is added to the database by the addMessageToDB(), which again calls the getMessageFromDatabase() to get all the messages.
@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),
);
}
)
}