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, Ethereal allows you to simply define them in a custom array.

    public static $relationsData = array(
        'country' => array(self::BELONGS_TO, Country::class, 'country_a2'),
        'profile' => array(self::HAS_MANY, Profile::class),
        'balances' => array(self::HAS_MANY, Balance::class),
    );

A complete list of example relationships can be found below. It is basically the function name in the first field of the array, followed by the function arguments.

    array(
        'relationship-name' => array(self::MORPH_TO, $name, $type, $id),
        'relationship-name' => array(self::MORPH_MANY, $related, $name, $type, $id, $localKey),
        'relationship-name' => array(self::MORPH_ONE, $related, $name, $type, $id, $localKey),
        'relationship-name' => array(self::MORPH_TO_MANY, $related, $name, $table, $foreignKey, $otherKey, $inverse),
        'relationship-name' => array(self::MORPH_BY_MANY, $related, $name, $table, $foreignKey, $otherKey),
        'relationship-name' => array(self::BELONGS_TO, $related, $foreignKey, $otherKey, $relation),
        'relationship-name' => array(self::BELONGS_TO_MANY, $related, $table, $foreignKey, $otherKey, $relation),
        'relationship-name' => array(self::HAS_MANY, $related, $foreignKey, $localKey),
        'relationship-name' => array(self::HAS_ONE, $related, $foreignKey, $localKey),
        'relationship-name' => array(self::HAS_MANY_THROUGH, $related, $foreignKey, $localKey),
        'relationship-name' => array(self::HAS_MANY_THROUGH_CUSTOM, $related, $foreignKey, $localKey),
    )

Custom Has Many Through

This function has been added to enable a relationships between two tables on a dual primary key basis. Take this table structure example.

game
    id - integer
    name - string

player
    id - integer
    name - string

player_games
    game_id - integer
    player_id - integer
    played_at - date

This relationship will allow a player to retrieve all the games played directly through a joiner table.

Clone this wiki locally