popolo - code simple..

popolo - code simple..

Masonite Project - Many to Many Relationship Example

Masonite Project - Many to Many Relationship Example

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

3 min read

In this article, we will see how many to many relationship is implemented in Masonite project.

The key in many to many relationship is the join (or pivot) table. The pivot table allows the relationship id from one model to be related to many other models and vice-versa.

Many-to-many relationships are defined by writing a method that returns the result of the belongs_to_many.

In our example, Multiple Categories have Multiple Posts, and an inverse relationship will be Multiple Posts belongs to Multiple Categories.

So, what we will do is that, when we go to a particular category, we need to display all the Posts.

Same, when we see the particular Post, we need to display all the Categories that this Post belongs to.

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 categories migration file.

python craft migration create_categories_table --create categories

categories table migration

"""CreateCategoriesTable Migration."""

from masoniteorm.migrations import Migration


class CreateCategoriesTable(Migration):
    def up(self):
        """
        Run the migrations.
        """
        with self.schema.create("categories") as table:
            table.increments("id")
            table.string("title")
            table.timestamps()

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

Now we must create the pivot table that will keep the relationship between Post and Category. According to the Masonite documentation, the name of the pivot table is the singular form of both table names in alphabetical order. For our example, the table name must be category_post. Run now the migrations.

We are creating the category_post migration file.

python craft migration create_category_post_table --create category_post

category_post table migration

"""CreateCategoryPostTable Migration."""

from masoniteorm.migrations import Migration


class CreateCategoryPostTable(Migration):
    def up(self):
        """
        Run the migrations.
        """
        with self.schema.create("category_post") as table:
            table.increments("id")
            table.integer("category_id").unsigned()
            table.foreign("category_id").references("id").on("categories")
            table.integer("post_id").unsigned()
            table.foreign("post_id").references("id").on("posts")
            table.timestamps()

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

Run now the migrations.

python craft migrate

Create Models

We must firstly create Post.py .

python craft model Post

Post.py

@belongs_to_many('post_id','category_id','id','id') The first 2 keys are the foreign keys relating from posts to categories through the pivot table and the last 2 keys are the foreign keys on the posts and categories table.

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


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

    @belongs_to_many('post_id','category_id','id','id')
    def categories(self):
        from app.models.Category import Category
        return Category
python craft model Category

Category.py

@belongs_to_many('category_id', 'post_id','id','id') The first 2 keys are the foreign keys relating from categories to posts through the pivot table and the last 2 keys are the foreign keys on the categories and posts table.

""" Category Model """

from masoniteorm.models import Model
from masoniteorm.relationships import belongs_to_many



class Category(Model):
    """Category Model"""

    @belongs_to_many('category_id', 'post_id','id','id')
    def posts(self):
        from app.models.Post import Post
        return Post

Create Records (posts)

Now we will use tinker to create posts and categories.Then we will assign posts to relevant category and we will query them. 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"
    )

Now, we will create some categories.

Category.create(
        title="First Category"
    )
Category.create(
        title="Second Category"
    )

Now let's assign first category to first post.

post=Post.first()
category=Category.first()
#Assign category to post
post.attach('categories',category)

Let's see for the categories that are assigned to the first post.

post.categories.serialize()

#Outcome is:
[{'id': 1,
  'title': 'First Category',
  'created_at': '2022-04-21T10:39:39+00:00',
  'updated_at': '2022-04-21T10:39:39+00:00',
  'category_post_id': 1,
  'pivot': {'post_id': 1, 'category_id': 1, 'id': 1}}]

That's it! Now you can explore more about Masonite Many to Many Relationship!

 
Share this