popolo - code simple..

popolo - code simple..

Masonite Project- One to Many Relationship Example

Masonite Project- One to Many Relationship Example

Theodoros Kafantaris's photo
Theodoros Kafantaris
·Apr 21, 2022·

2 min read

Table of contents

  • Install Masonite
  • Create Migrations
  • Create Models
  • Create Records (posts)
  • Test the relationship

Another relationship is a one-to-many where a record in one table relates to many records, in another table. In this example, we will create posts and comments table. The relationship will be 1 post has many comments. But every comment belongs to one post.

Let's start with installation guide for Masonite Project Framework.

Install Masonite

How to install Masonite Project

Create Migrations

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.timestamps()

    def down(self):
        """
        Revert the migrations.
        """
        self.schema.drop("posts")

We are creating the comments migration file.

python craft migration create_comments_table --create comments

comments table migration

"""CreateCommentsTable Migration."""

from masoniteorm.migrations import Migration


class CreateCommentsTable(Migration):
    def up(self):
        """
        Run the migrations.
        """
        with self.schema.create("comments") as table:
            table.increments("id")
            table.string("title")
            table.integer('post_id').unsigned()
            table.foreign('post_id').references('id').on('posts')
            table.timestamps()

    def down(self):
        """
        Revert the migrations.
        """
        self.schema.drop("comments")

Run now the migrations.

python craft migrate

Create Models

We must firstly create Post.py .

python craft model Post

Post.py

""" Post Model """
from masoniteorm.models import Model
from masoniteorm.relationships import has_many


class Post(Model):
    """Post Model"""
    __fillable__ = ['title', 'user_id']

    @has_many('post_id','id')
    def comment(self):
        from app.models.Comment import Comment
        return Comment

Now it is time to create Comment.py .

python craft model Comment

Comment.py

""" Comment Model """

from masoniteorm.models import Model
from masoniteorm.relationships import belongs_to


class Comment(Model):
    """Comment Model"""
    __fillable__ = ["title", "post_id"]

    @belongs_to
    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
    )

Now, we will create some comments.

#First Comment
Comment.create(
        title="Comment 1",
        post_id=1
    )
#Second Comment
Comment.create(
        title="Comment 2",
        post_id=1
    )

Test the relationship

Get the comments for the first post.

Post.first().comments.serialize()
Out[4]: 
[{'id': 1,
  'title': 'Comment 1',
  'post_id': 1,
  'created_at': '2022-04-19T22:09:32+00:00',
  'updated_at': '2022-04-19T22:09:32+00:00'},
 {'id': 2,
  'title': 'Comment 2',
  'post_id': 1,
  'created_at': '2022-04-19T22:09:40+00:00',
  'updated_at': '2022-04-19T22:09:40+00:00'}]

Count the comments for the first post

Post.first().comments.count()
Out[6]: 2

Get the post of the first comment.

Comment.first().post.serialize()
Out[5]: 
{'id': 1,
 'title': 'First Post',
 'user_id': 1,
 'created_at': '2022-04-17T19:48:53+00:00',
 'updated_at': '2022-04-17T19:48:53+00:00'}
 
Share this