vendredi 13 septembre 2019

Laravel Relationships (Polymorphic Relationship)

I have 3 Models; Category, Event and Place. The relationship between these models is defined below.

A Category can have many events or places. A Place can have one category. An Event can have one category.

A Category belongs to either an event or a place.

This is what I have in my models.

Place.php

/**
 * Get category of a place
 *
 * @return Illuminate\Database\Eloquent\Relations\MorphOne;
 */
public function category()
{
    return $this->morphOne(Category::class, 'categorable');
}

Event.php

Event.php
/**
 * Get all of the owning eventable models
 *
 * @return Illuminate\Database\Eloquent\Relations\MorphTo;
 */
public function eventable()
{
    return $this->morphTo();
}

Category.php

/**
 * Get all of the owning categorable models.
 *
 * @return Illuminate\Database\Eloquent\Relations\MorphTo
 */
public function categorable()
{
    return $this->morphTo();
}

/**
 * Get all events that belong to a category
 *
 * @return Illuminate\Database\Eloquent\Relations\HasMany
 */
public function events()
{
    return $this->hasMany(Event::class);
}

/**
 * Get all places that belong to a category
 *
 * @return Illuminate\Database\Eloquent\Relations\HasMany
 */
public function places()
{
    return $this->hasMany(Place::class);
}

PS: I do have the category_id foreign key on both events and places.

Thank you very much.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2I6JzyZ
via IFTTT

Aucun commentaire:

Enregistrer un commentaire