dongzhuang2030
2013-11-16 12:56
浏览 75
已采纳

Laravel 4:神奇地称为belongsTo关系的奇怪行为

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.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsfo22654 2013-11-16 18:12
    已采纳

    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');
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题