dongzhuoxie1244 2016-12-14 00:34
浏览 36
已采纳

Laravel 5 One to One关系返回null

I have two models I am trying to create a one to one relationship for: A Week model and WeekType model. The WeekType belongs to Week, and should be a one to one relationship.. however, Laravel is returning null on a dd(Week::find($id)->weektpye);

Here are my models:

Week.php

public function weekTypes()
{
    return $this -> hasOne('App\WeekType');
}

WeekType.php

public function weeks()
{
    return $this -> belongsTo('App\Week');
}

And my schema:

http://imgur.com/K2XhJVB

I feel I'm missing something obvious or my schema is incorrectly configured, though I'm not sure how.

  • 写回答

1条回答 默认 最新

  • duanfengshang1088 2016-12-14 00:48
    关注

    I think you might be mixing up singular and plural naming. It looks like you are trying to access the singular version in your dd(), but have named it plural. Also, there is a typo in the dd(). Your Schema looks okay, so I believe the following should work for you.

    Week.php

    public function weekType()
    {
        return $this->hasOne('App\WeekType', 'week_type_id');
    }
    

    WeekType.php

    public function weeks()
    {
        return $this->belongsTo('App\Week', 'week_type_id');
    }
    

    After that the following should work for you.

    dd(Week::find($id)->weekType);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 spring后端vue前端
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题