Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to create with model relationship? #498

Closed
Mozzarella-dev opened this issue Sep 3, 2021 · 3 comments
Closed

How to create with model relationship? #498

Mozzarella-dev opened this issue Sep 3, 2021 · 3 comments

Comments

@Mozzarella-dev
Copy link

I've got two tables, one called users and one called posts. In the posts table i've got a foreign key to the id of the users table and i've defined one to many relationship between User and Post.

My problem is the following: can't create a Post in the database because the column user_id (the foreign key) doesn't have a default value.

First i create a User with the following function:

def create_user(name):
   return User.create({'name': name})

# Executing it like this:
new_user = create_user('John')

After that i try to create a Post:

def create_post(user, title):
   return Post.create({'title': title, 'user_id': user.id})

# Executing it like this:
new_post = create_post(new_user, 'Hello World')

When executing the second function i get the following error:

masoniteorm.exceptions.QueryException: (1364, "Field 'user_id' doesn't have a default value")

I've used Eloquent in the past but in php and i don't know how to translate to python the following code:

$user = User::create($userData);
$user->post()->create($postData);

I've tried the following without success (even without the parenthesis after post):

user.post().create({'title': title})

This may seem a stupid hiccup to some but couldn't find anything in the documentation unfortunatelly.
Thanks in advance for the help.

@josephmancuso
Copy link
Member

Theres 2 things you can do:

  1. Make the user_id nullable on the Posts table and just make sure the user_id always gets set on the posts table:
def create_post(user, title):
   return Post.create({'title': title, 'user_id': user.id})

new_post = create_post('Hello World')

new_post.user_id = user.id

This way you just ensure data integrity at the application level.

Or option 2 I believe you can do it all inside a single transaction and then commit the transaction

@josephmancuso
Copy link
Member

@Mozzarella-dev sorry I think I misunderstood your original issue. Does your Post model have user_id in the __fillable__ attribute?

@Mozzarella-dev
Copy link
Author

@josephmancuso crap, that was my problem, didn't set it fillable for mass assignment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants