0

Suppose there is a two tables "User" and "Product", so there is also a foreign key, that means, that one user can have multiple products, like:

CREATE TABLE "user" (

  id BIGSERIAL NOT NULL,
  Name VARCHAR(100) NOT NULL,

  ProductId PRIMARY KEY,  
  Products FOREIGN KEY(ProductId) REFERENCES product(id)

)

CREATE TABLE "product"(
    id BIGSERIAL NOT NULL PRIMARY KEY,
    product_name VARCHAR(100) NOT NULL,
)

The problem is when I'm creating a new user I don't specify ProductId, (because for example product does not exist yet) it always it throws an exception, that ProductId has a unique constraint and should be not null.

So What I Need to Put Inside ProductId?

Because I don't specify any value for it when creating User, it throws unique constraint error, but without this Field I cannot have a foreign key between two tables, so it cannot be removed.

So, the question is "How can I Specify Default Value for This Reference "ProductId" Field in My "User" model, when creating an user object, in order to avoid this unique constraint error."

4
  • 1
    Well, you will need to create the product first. But a column named productid as the primary key for a table named user sounds extremely weird to me. Why isn't user.id the primary key? And why is a user only related to a single product? That sounds like a strange decision to me as well. Commented Aug 1, 2022 at 6:38
  • this question telles you how to create a column with a default value: mysql, Create Column with a default value. It should have enough info to specify a default value for your column . (But, I think, the problem lies elsewhere...) Commented Aug 1, 2022 at 6:38
  • Sorry, I've been using ORMs for a long time, and pretty rarely been dealing with a raw sql, I recently switched to Golang, and there is a bit another implementation of foreign keys, so I'm getting used to it, so WHAT I WANT IS to make "one object" have a lot of another's :) Commented Aug 1, 2022 at 6:41
  • If a user can be "have" many products, you need a many-to-many relationship between user and product. If a product can only ever be "owned" by a single user, then product should have a foreign key to user. Your current model would allow a user to "have" only a single product. Commented Aug 1, 2022 at 6:50

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.