Question

I have the following Task Model

class Task extends Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
}

When I call:

$task = Task::with('user')->first();

I get the following expected result:

{
    id      : 10,
    user_id : 20,
    user    : {
        id      : 20
    }
}

And the following expected Query-log:

select `tasks`.* from `tasks` limit 1;
select * from `users` where `users`.`id` in (20);

However, when I set my relationship in a magical way, the belongsTo relationship breaks:

class Task extends Eloquent {
    public function __call($name, $arguments)
    {
        if ($name === 'user')
            return $this->belongsTo('User');

        return parent::__call($name, $arguments);
    }
}

I get the following broken result:

{
    id      : 10,
    user_id : 20,
    user    : null // USER IS MISSING!
}

And the following broken Query-log:

select `tasks`.* from `tasks` limit 1;
select * from `users` where `users`.`id` in (0); // NOTE THE 0 INSTEAD OF 20

I don't get any error. I've tried the same thing with belongsToMany, but that works perfectly.

For some reason the '20' doesn't get passed to the belongsTo relationship. Therefore I expect the __call() is firing up a new query instance, but I don't understand why?

I have logged the times __call() gets fired, but besides the 'user' method, it doesn't seem to get fired at all. So to my knowledge that cannot be the issue then.

Was it helpful?

Solution

That's probably because Laravel uses the name of the method it's inside as the default foreign key. Try this:

return $this->belongsTo('User', 'user_id');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top