Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

hasManyToMany with two models

Hi guys. 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:

$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:

$entities = $group->subgroups->entities;

And is it possible at all?



2.6k
Accepted
answer
edited Oct '15

If you have

class Group extends Model 
{
    public $id;
    public $name;

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

You should be able to

$entities = $group->entities;

You can keep your hasMany relations, still.

Edit: Yeah it was a typo. I've changed it, in my post aswell. Im glad that it made sense.

edited Oct '15

Thanks alot !

Works if I replace last id with subgroupid - guess it was typo:

class Group extends Model 
{
    public $id;
    public $name;

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