我在使用Laravel时遇到了一个非常奇怪的问题。
我有4张表(还有更多,但它们与问题无关):
platoons
- id
- game_id
- leader_id
- name
games
- id
- name
- icon
game_user_info_fields
- id
- game_id
- user_info_id
user_info_fields
- id
- name
这些表的模型包含以下关系方法:
class Platoon extends 'Eloquent {
public function game() {
return $this->belongsTo('Game');
}
}
class Game extends 'Eloquent {
protected $fillable = [];
protected $table = 'games';
public function fields() {
return $this->hasMany('GameUserInfoField');
}
}
class GameUserInfoField extends 'Eloquent {
protected $fillable = [];
protected $table = 'game_user_info_fields';
public function field() {
return $this->belongsTo('UserInfoField');
}
public function game() {
return $this->belongsTo('Game');
}
}
class UserInfoField extends 'Eloquent {
protected $fillable = [];
protected $table = 'user_info_fields';
public function fields() {
return $this->hasOne('GameUserInfoField');
}
}
表格数据:
platoons
id game_id leader_id name
1 1 1 Battlefield 4
2 2 1 CS:GO
3 3 1 LoL
4 4 1 GTAV
games
id name icon
1 Battlefield 4 bf4.png
2 CS:GO csgo.png
3 League of Legends lol.png
4 GTA V gtav.png
game_user_info_fields
id game_id user_info_field_id
1 1 1
2 1 2
3 2 3
4 3 4
5 4 5
user_info_fields
id name
1 Origin username
2 Battlelog link
3 Steam ID
4 LoL username
5 Social club username
问题:
(HLP::pp()方法是一个助手,类似于函数dd())
$platoon = Platoon::where('id', '=', Input::get('platoon_id'))->first();
foreach ($platoon->game->fields as $gameuserinfofield) {
HLP::pp($gameuserinfofield->field);
}
返回NULL,当它应该返回UserInfoField模型时,而
foreach ($platoon->game->fields as $gameuserinfofield) {
HLP::pp($gameuserinfofield->game);
}
返回游戏模型。
它们都有相同的关系,只是不同的表,所以我不明白它是如何无法检索模型的。。。
直接通过检索模型
UserInfoField::all();
确实检索了模型,这是应该的。
在过去的4个小时里,我一直被困在这个问题上,无法修复,请帮帮我!
您的关系过于复杂。你可以简单地指定它们是什么。一种多对多的关系。这是使用belongsToMany()
:完成的
public function fields(){
return $this->belongsToMany('UserInfoField');
}
这种新的关系使得GameUserInfoField
模型完全过时。