Nozbe / WatermelonDB

🍉 Reactive & asynchronous database for powerful React and React Native apps ⚡️
https://watermelondb.dev
MIT License
10.49k stars 589 forks source link

Relations using custom key #1789

Open PROda221 opened 4 months ago

PROda221 commented 4 months ago

Hello everyone!

I want to create a simple 1 to 1 chat system where there are 2 models, Chat and Message. Every chat can have many messages and each message belongs to only one chat.

My Chat Model:-

`import { Model } from '@nozbe/watermelondb'; import { date, field, readonly, children } from '@nozbe/watermelondb/decorators';

image

Message Model:- image

Schema:- import {appSchema, tableSchema} from '@nozbe/watermelondb'; image

Setting chats with my custom "chat_id" is fine, but when I try to set messages with this chat_id it is not set inside _raw but on the Message object itself...

Using this function to create new messages:-

image

Response I am getting when new message is created:- {"__changes": {"_value": [Circular], "closed": false, "currentObservers": null, "hasError": false, "isStopped": false, "observers": [], "thrownError": null}, "_isEditing": false, "_preparedState": null, "_raw": {"_changed": "", "_status": "created", "chat_id": "", "created_at": 1714842531304, "id": "zxNLPlK8CSJ1cYwB", "is_received": false, "text": "dddd", "updated_at": 1714842531304}, "_relationCache": {"chat": {"_columnName": "chat_id", "_isImmutable": false, "_model": [Circular], "_relationTableName": "chats"}}, "_subscribers": [], "collection": {"_cache": {"_debugCollection": [Circular], "map": [Map], "recordInsantiator": [Function anonymous], "tableName": "messages"}, "_subscribers": [], "changes": {"closed": false, "currentObservers": [Array], "hasError": false, "isStopped": false, "observers": [Array], "thrownError": null}, "database": {"_isBeingReset": false, "_isBroken": false, "_pendingNotificationBatches": 0, "_pendingNotificationChanges": [Array], "_resetCount": 0, "_subscribers": [Array], "_workQueue": [WorkQueue], "adapter": [DatabaseAdapterCompat], "collections": [CollectionMap], "schema": [Object]}, "modelClass": [Function Message]}}

Any idea!?? I am fairly new to this.

primus11 commented 4 months ago

Each model/table will automatically get id. When defining relations it is this automatic id that is used. So you should probably lose your custom chat_id. Check also Relations where in first example your Message is really Comment and your Chat is User.