表格:
Posts
id | console_id | game_id | etc
Games
id | name
Console
id | name
现在,当我查询这个关系时,我不断地得到"尝试获取非对象的属性"错误。现在,如果我把我的结果限制在前三名(这是我在游戏表上的全部),那么它会运行,但除此之外,它会抛出异常。。。这种关系错了吗?
关系:
Game
public function Post()
{
return $this->belongsTo('AppPost', 'game_id');
}
Post
public function console()
{
return $this->hasOne('AppConsole', 'id');
}
public function games()
{
return $this->hasOne('AppGame', 'id');
}
Console
public function Post()
{
return $this->belongsTo('AppPost', 'console_id');
}
更新
@joel@rashmi所以实际上我在第四篇文章中看到了这篇文章。。。它返回空
["relations":protected]=>
array(2) {
["games"]=>
NULL
前3个返回值。但随后第4个on都返回NULL。同样,我在游戏表中只有3个值
Games Table:
1 | game 1
2 | game 2
3 | game 3
实际上,在第三个条目上,它的值为2,但显示了游戏3的名称
posts table:
id | game id
1 | 2
2 | 3
3 | 2 (but showing "game 1" text)
看起来你的帖子都属于一个控制台和一个游戏,而不是相反。hasOne意味着只能有一个,但每个主机和游戏都可以有很多帖子。所以应该是这样的:
// Game
public function posts()
{
return $this->hasMany('AppPost');
}
// Post
public function console()
{
return $this->belongsTo('AppConsole');
}
public function game()
{
return $this->belongsTo('AppGame');
}
// Console
public function posts()
{
return $this->hasMany('AppPost');
}
如果你的表分别命名为控制台、游戏和帖子,那么你不需要提供id,所以我删除了它们。如果需要,您可以重新添加它们。
你们之间的关系似乎不合适。应该是这样的:
// Game Model
public function posts()
{
return $this->hasMany('AppPost');
}
// Post Model
public function console()
{
return $this->belongsTo('AppConsole');
}
public function game()
{
return $this->belongsTo('AppGame');
}
// Console Model
public function posts()
{
return $this->hasMany('AppPost');
}
你对帖子的Eloquent查询将是:
$this->model->select(SELECTED_FIELDS)
->with(array('game','console'))
->get();
其中SELECTED_FIELDS表示要获取的表字段。