In this tutorial we will explore One to One Relationship in Masonite Project.
One to One model relationship is very simple and basic. We have to make sure that one of the tables has a key that references the id of the other table. We will learn how we can create migration with foreign key schema, retrieve records, insert new records, update records, etc.
In this example, we will use users
table and we will create the posts
table.
Please find the installation guide for Masonite Project Framework.
Install Masonite
How to install Masonite Project
Create Migrations
users table migration
from masoniteorm.migrations import Migration
class CreateUsersTable(Migration):
def up(self):
"""Run the migrations."""
with self.schema.create("users") as table:
table.increments("id")
table.string("name")
table.string("email").unique()
table.string("password")
table.string("second_password").nullable()
table.string("remember_token").nullable()
table.string("phone").nullable()
table.timestamp("verified_at").nullable()
table.timestamps()
table.soft_deletes()
def down(self):
"""Revert the migrations."""
self.schema.drop("users")
We are creating the posts
migration file.
python craft migration create_posts_table --create posts
posts table migration
"""CreatePostsTable Migration."""
from masoniteorm.migrations import Migration
class CreatePostsTable(Migration):
def up(self):
"""
Run the migrations.
"""
with self.schema.create("posts") as table:
table.increments("id")
table.string("title")
table.integer('user_id').unsigned()
table.foreign('user_id').references('id').on('users')
table.timestamps()
def down(self):
"""
Revert the migrations.
"""
self.schema.drop("posts")
Run now the migrations.
python craft migrate
Create Models
We must firstly create Post.py
.
python craft model Post
""" Post Model """
from masoniteorm.relationships import belongs_to
from masoniteorm.models import Model
class Post(Model):
"""Post Model"""
__fillable__ = ['title', 'user_id']
@belongs_to
def user(self):
from app.models.User import User
return User
"""User Model."""
from masoniteorm.models import Model
from masoniteorm.scopes import SoftDeletesMixin
from masonite.authentication import Authenticates
from masoniteorm.relationships import has_one
class User(Model, SoftDeletesMixin, Authenticates):
"""User Model."""
__fillable__ = ["name", "email", "password"]
__hidden__ = ["password"]
__auth__ = "email"
@has_one('user_id','id')
def post(self):
from app.models.Post import Post
return Post
Create Records (posts)
Now we will use tinker to create posts and assign them to users. You can find how to use tinker following the below link.
How to use Masonite Tinker Shell
Connect to tinker.
python craft tinker -i
We will create a post.
Post.create(
title="First Post",
user_id=1
)
Test the relationship
Get the user for the 1st post.
Post.first().user.serialize()
Get the post of the first user.
User.find(1).post.serialize()
I hope that it helps you to make clearer this topic.