Inserting Knex.js from selected

I am trying to create a request like the following via Knex.js:

INSERT INTO table` ("column1", "column2")
SELECT "someVal", 12345)
    SELECT 1
    FROM table
    WHERE "column2" = 12345


Basically, I only want to insert values ​​if the specific value doesn't exist yet. But Knex.js doesn't seem to know how to do this; if i call knex.insert()

(no values) it generates an "insert default values" query.

I tried the following:



but that still gives me the default. I tried adding .columns(Object.keys(data))

in the hopes that it would insert()

accomplish this, but no luck.

Is it possible to generate the request I want using knex, or do I just need to create a raw request without Knex.js methods?


source to share

1 answer

I believe the selection should be passed into the insert:



Also to select constant values ​​or expressions, you need to use knex.raw expression in select:"'someVal',12345")).from("tableName")


This is my first post and I haven't tested your specific example, but I have done similar things like what you are asking using the above methods.



All Articles