laravel belongsTo gives null

∥☆過路亽.° 提交于 2019-12-04 05:37:40

问题


belongsTo relation in laravel is returning null

public function games(){
    return $this->belongsTo('App\Models\Game');
  }

but when i provide key as argument it seems to work fine

  public function games(){
        return $this->belongsTo('App\Models\Game','game_id');
      }

but as per the docs game_id is itself is a default argument. What is the small thing i am missing here.

Thanks


回答1:


The belongsTo side of the relationship builds the foreign key name based on the name of the relationship method. This behavior is different than the hasOne/hasMany side of the relationship, which uses the name of the class.

In this case, your relationship method is named games, so it will look for the foreign key field games_id. You can either provide the foreign key field as the second parameter, as you have shown, or you can rename your relationship method to game().




回答2:


It looks like the name of your method "games" may be the issue. The assumption with a 1-to-many relationship is that the parent class is singular while the child is plural. Try changing the name "games" to "game" and the key argument shouldn't be required.

At this point, I'm guessing Laravel is thinking your id key would be "games_id".




回答3:


In my case, i was using public for defining variables. When I change to protected it worked.

public $fillable = [..class properties..];

changed to

protected $fillable = [..class properties..];


来源:https://stackoverflow.com/questions/37971628/laravel-belongsto-gives-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!