問題描述
laravel 中的 belongsTo 關系返回 null
belongsTo relation in laravel is returning null
public function games(){
return $this->belongsTo('AppModelsGame');
}
但是當我提供密鑰作為參數時,它似乎工作正常
but when i provide key as argument it seems to work fine
public function games(){
return $this->belongsTo('AppModelsGame','game_id');
}
但根據 docs game_id
本身就是一個默認參數.我在這里缺少什么小東西.
but as per the docs game_id
is itself is a default argument. What is the small thing i am missing here.
謝謝
推薦答案
關系的 belongsTo
端根據關系方法的名稱構建外鍵名稱.這種行為不同于關系的 hasOne
/hasMany
端,后者使用類的名稱.
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.
在本例中,您的關系方法名為 games
,因此它將查找外鍵字段 games_id
.您可以提供外鍵字段作為第二個參數,如您所示,或者您可以將您的關系方法重命名為 game()
.
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()
.
這篇關于laravel ownsTo 給出 null的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!