dongzhuoxie1244 2016-12-13 16: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-13 16: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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部