DEV Community

Kentaro0919
Kentaro0919

Posted on

Orator has many through

Relationship has-many-through

The orator has many functions around relationships. In the current

  • One To One
  • One To Many
  • Many To Many
  • Has Many Through <- I am writing about this
  • Polymorphic relations
  • Many To Many polymorphic relations

Models are like this.

#app.Country
"""Countrie Model"""

from config.database import Model
from orator.orm import has_many_through, has_many


class Country(Model):
    """Countrie Model"""

    __table__ = "countries"
    __fillable__ = ['name']
    from app.User import User

    @has_many("country_id", "id")
    def users(self):
        from app.User import User
        return User

    @has_many_through(User, 'country_id', 'user_id')
    def posts(self):
        from app.Post import Post
        return Post
# app.User

"""User Model."""

from config.database import Model
from orator.orm import belongs_to_many, has_many

class User(Model):
    """User Model."""

    __fillable__ = ['name', 'email', 'password', 'country_id']

    __auth__ = 'email'

    @has_many
    def posts(self):
        from app.Post import Post
        return Post
# app.Post
"""Post Model"""

from config.database import Model
from orator.orm import belongs_to


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

    @belongs_to
    def user(self):
        from app.User import User
        return User

database

The controller is very simple, just all()

""" A testController Module """
from app.Country import Country
from masonite.view import View

class testController:

    def index(self, view: View):
        """Show several resource listings
        ex. Model.all()
            Get().route("/index", testController
        """

        countrys = Country.all()
        return view.render("index", {"countrys": countrys})

Now it is possible to user and post in the view.

<ul>
    {% for country in countrys %}
        <li>{{ country.id }} {{ country.name }}
            <ul>
            This comes from Country.users has_many
                {% for user in country.users %}
                    <li>{{ user.name }}
                        <ul>
                            {% for post in user.posts %}
                            <li>{{ post.title }}</li>
                                {% endfor %}
                        </ul>
                    </li>
                {% endfor %}
            </ul>
            <ul>
            This comes from Country.posts has_many_through User
                {% for post in country.posts %}

                    <li>{{ post.title }} {{ post.user.name }}</li>
                {% endfor %}
            </ul>
        </li>
    {% endfor %}
</ul>

Discussion (0)