denodb icon indicating copy to clipboard operation
denodb copied to clipboard

Nullable foreignkey

Open ddorstijn opened this issue 4 years ago • 2 comments

Is there a way to add a "one to zero or one" relationship at the moment? It seems like the not null constraint is added automatically and there seems no way to go around it? I saw a closed issue about creating the relationship manually but I cannot find documentation on how to do this.

EDIT:

So I tried to do it manually, creating a relationship field with allowNull set to true, like so:

export default class Present extends Model {
    static table = 'presents';
    
    static fields = {
        id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
        name: { type: DataTypes.STRING, length: 128 },
        url: { type: DataTypes.STRING, length: 256, allowNull: true },
        familyId: {
            type: DataTypes.INTEGER,
            allowNull: true,
            relationship: {
                kind: "single" as const,
                model: Family,
            },
        }
    }
}

Unfortunately I still get the following error:

Error: Column 'family_id' cannot be null

ddorstijn avatar May 16 '21 14:05 ddorstijn

Hi, @ddorstijn. Is that the complete error's message? And if not. Could you show all the message in order to understand where is throwing the error?

jrdx0 avatar May 17 '21 05:05 jrdx0

I assumed the error log would probably be related to the null constraint, so I thought it would not be of use. The full error message is as follows:

Error: Column 'family_id' cannot be null
    at PoolConnection.nextPacket (https://deno.land/x/[email protected]/src/connection.ts:185:13)
    at async PoolConnection.execute (https://deno.land/x/[email protected]/src/connection.ts:263:21)
    at async https://deno.land/x/[email protected]/src/client.ts:97:14
    at async Client.useConnection (https://deno.land/x/[email protected]/src/client.ts:107:14)
    at async Client.execute (https://deno.land/x/[email protected]/src/client.ts:96:12)
    at async MySQLConnector.query (https://deno.land/x/[email protected]/lib/connectors/mysql-connector.ts:79:22)
    at async Database.query (https://deno.land/x/[email protected]/lib/database.ts:240:21)
    at async Function._runQuery (https://deno.land/x/[email protected]/lib/model.ts:228:21)
    at async Function.create (https://deno.land/x/[email protected]/lib/model.ts:449:21)
    at async createPresent (file:///home/ddorstijn/Documents/Web/trouwerij-deno/controllers/present.ts:24:22)

ddorstijn avatar May 18 '21 07:05 ddorstijn