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.

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?



19.6k
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');
    }
}


84.5k

It must work:

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

Could you var_dump($curso); please?



19.6k

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.



19.6k
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...