We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Docs "Robots" realtion example not working

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public $id;

    public $name;

    public function initialize()
    {
        $this->hasManyToMany(
            'id',
            'RobotsParts',
            'robots_id', 'parts_id',
            'Parts',
            'id'
        );

    }
}

class Parts extends Model
{
    public $id;

    public $name;

    public function initialize()
    {
        $this->hasMany(
            'id',
            'RobotsParts',
            'parts_id'
        );
    }
}

class RobotsParts extends Model
{
    public $id;

    public $robots_id;

    public $parts_id;

    public function initialize()
    {
        $this->belongsTo(
            'robots_id',
            'Robots',
            'id'
        );

        $this->belongsTo(
            'parts_id',
            'Parts',
            'id'
        );
    }
}

$robot = Robots::findFirst(1);

foreach ($robot->robotsParts as $robotPart) {
    echo $robotPart->parts->name, "\n";
}

https://docs.phalcon.io/en/3.1/db-models-relationships

Error: Access to undefined property ... I also tried "$robot->parts"

At same time $robots->_modelsManager->_aliases has a relation keyed "robots$parts" And this code resolves a realtion correct

$rel = $robot->getModelsManager()->getRelationByAlias(get_class($robot), 'Parts');

and this works (gets the records) $robot->getModelsManager()->getRelationRecords($rel, null, $robot, null)

ver 3.2.2

Hi @Mikola the problem is $robot->parts that "parts" are a Resultset. You have to do

$robot = Robots::findFirst(1);

foreach ($robot->robotsParts as $robotPart) {
    foreach($robotPart->parts as $part) {
        echo $part->name, "\n";
    }
}

Other way and better for me, is set alias to all yours relationships and always use $model->getRelated("your-rel-alias")

Good luck

edited Oct '17

@Degiovanni, thanks, the problem is in doc text itself - code shoule be

foreach ($robot->parts as $robotPart) {
    echo $robotPart->name, "\n";
}

figured out in experimental way. Code you gave will not work (yes, i have tried) as no relation named robotsParts exists in manager of Robot (parts exists, or in system name robots$parts

Yes, i like idea with setting manual alias to reltionship like here https://forum.phalcon.io/discussion/545/many-to-many-relation

    public function initialize()
    {
        $this->hasManyToMany(
             "category",
             "Calin\Core\Models\ArticlesCategories",
             "article_id",
             "category_id",
             "Calin\Core\Models\Category",
             "id",
             array('alias' => 'Categories')
        );
    }