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

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

相关推荐 更多相似问题