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

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路