Skip to content

HasDynamicRelationships

Kevin Upton edited this page Nov 30, 2017 · 3 revisions

The HasDynamicRelationships trait handles relationships a little bit differently. Instead of creating a function for each relationship like in the Laravel Model, HasDynamicRelationships allows you to define them in a $relationships array.

Example

Note the class comments. These assist the IDE in knowing whats on the class.

use Illuminate\Database\Eloquent\Model;

/**
 * @property Country country
 * @property Profile[] profiles
 * @property Balance[] balances
 * @method Relation country
 * @method Relation profiles
 * @method Relation balances
 */
class BaseModel extends Model implements RelationshipConstants
{
    use HasDynamicRelationships;

    public $relationships = array(
        'country' => [self::BELONGS_TO, Country::class, 'country_a2'],
        'profiles' => [self::HAS_MANY, Profile::class],
        'balances' => [self::HAS_MANY, Balance::class],
    );

}

RelationshipConstants

Implement this interface to get access to all the constants

<?php

namespace Kevupton\Ethereal\Models;

interface RelationshipConstants
{
    const HAS_MANY = "hasMany";
    const HAS_ONE = "hasOne";
    const BELONGS_TO_MANY = "belongsToMany";
    const BELONGS_TO = "belongsTo";
    const MORPH_TO_MANY = "morphToMany";
    const MORPH_BY_MANY = "morphByMany";
    const MORPH_TO = "morphTo";
    const MORPH_ONE = "morphOne";
    const MORPH_MANY = "morphMany";
    const HAS_MANY_THROUGH = 'hasManyThrough';
    const HAS_MANY_THROUGH_CUSTOM = 'hasManyThroughCustom';
}