phpmodelrelationshipphalcon

hasManyToMany relation with two tables


Is it possible to make many to many relation with 2 tables ? Lets say I have following structure:

<?php
use Phalcon\Mvc\Model;

/**
entity
-id
-name
-sub_group_id
*/
class Entity extends Model {

    public $id;
    public $name;
    public $sub_group_id;

    public function initialize()
    {
        $this->belongsTo('sub_group_id', 'SubGroup', 'id', ['alias' => 'subgroup']);
    }
}

/**
sub_group
-id
-name
-group_id
*/
class SubGroup extends Model {

    public $id;
    public $name;
    public $group_id;

    public function initialize()
    {
        $this->belongsTo('group_id', 'Group', 'id', ['alias' => 'group']);
        $this->hasMany('id', 'Entity', 'sub_group_id', ['alias' => 'entities']);
    }
}

/**
group
-id
-name
*/
class Group extends Model {

    public $id;
    public $name;

    public function initialize()
    {
        $this->hasMany('id', 'SubGroup', 'group_id', ['alias' => 'subgroups']);
    }
}

So Group will have 'hasMany' relation to SubGroup. Subgroup will have 'hasMany' relation to Entity.

To get entities from group I use:

<?php

$entities = [];
$group = Group::findFirst();
foreach ($group->subgroups as $subgroup){
    $entities = array_merge($entities, $subgroup->entities->toArray());
}

What relation I should change to, lets say Subgroup will have 'hasManyXXX' relation to Entity.

To get following result:

<?php

$entities = $group->subgroups->entities->toArray();

And is it possible at all?


Solution

  • There is a way to do so !

    class Group extends Model 
    {
        public $id;
        public $name;
    
        public function initialize()
        {
            $this->hasManyToMany(
                'id',
                'SubGroup',
                'group_id',
                'id',
                'Entity',
                'sub_group_id',
                [
                    'alias' => 'entities'
                ]
            );
        }
    }
    

    Will give you an option to use:

    $entities = $group->entities;
    

    Credits to phalcon forum