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

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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Odoo17操作下面代码的模块时出现没有'读取'来访问
  • ¥50 .net core 并发调用接口问题
  • ¥15 网上各种方法试过了,pip还是无法使用
  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题