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

belongsTo understanding problem

I'm seeing the example that the docs gives:

$robotPart = RobotsParts::findFirst(1);

// RobotsParts model has a n-1 (belongsTo)
// relationship to RobotsParts then
$robot = $robotPart->robots;

I want to do the same, but with groups and grades. So it will be:

$group = Group::findFirst();

$grade = $group->grade;

But it isn't working. What I'm doing wrong? I didn't understand it well?

Can you show us how you've definied the relationship against both models? Are you using namespaces? Are you using aliases for the column/property names?



33.8k
edited Jul '14

No namespaces, aliases, or else. Only the models (Curso = Grade, Grupo = Group). 1-n relation (grade has many groups):

<?php

use Phalcon\Mvc\Model;

class Curso extends Model
{
    public function initialize()
    {
        $this->hasMany('id', 'Grupo', 'curso_id');
    }
}
<?php

use Phalcon\Mvc\Model;

class Grupo extends Model
{
    public function initialize()
    {
        $this->belongsTo('curso_id', 'Curso', 'id');
    }
}


98.9k

It must work:

$grupo = Grupo::findFirst();
$curso = $grupo->curso; // returns an instance of Curso or false

Could you var_dump($curso); please?



33.8k

Sorry for the waiting. I always do first a vardump to new things like this, and before I asked here it gives me NULL.

I get, from the DB, each row from each table. But when I try to get a Grade from a Group, it doesn't work.



33.8k
Accepted
answer

I just can't... I just can't continuing living in this world.

The error was that the models didn't uploaded correctly by the time I tried it (don't know why)...

I don't want to live anymore...