Laravel Eloquent关系只返回最小的结果

时间:2016-05-14 17:14:44

标签: laravel eloquent lumen

表格:

Posts
id | console_id | game_id | etc

Games
id | name

Console
id | name

现在,当我查询这种关系时,我不断得到“试图获取非对象的属性”错误。现在,如果我限制我的结果来说前三名(这是我在游戏表中的所有内容)那么它将会运行,但更多的是它会抛出异常......这种关系错了吗?

关系:

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

Post
public function console()
{
    return $this->hasOne('App\Console', 'id');
}

public function games()
{
    return $this->hasOne('App\Game', 'id');
}

Console
public function Post()
{
    return $this->belongsTo('App\Post', 'console_id');
}

更新

@joel @rashmi所以实际上在我的第四个条目上转储我发现的$ post ...它返回NULL

["relations":protected]=>
  array(2) {
    ["games"]=>
    NULL

前3个返回值。但是接下来的第四个都返回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)

2 个答案:

答案 0 :(得分:1)

看起来你的帖子都属于控制台和游戏 - 而不是相反。并且hasOne意味着只能有一个,但每个控制台和游戏可以有很多帖子。所以它应该是这样的:

// Game
public function posts()
{
    return $this->hasMany('App\Post');
}

// Post
public function console()
{
    return $this->belongsTo('App\Console');
}

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

// Console
public function posts()
{
    return $this->hasMany('App\Post');
}

如果您的表分别被命名为控制台,游戏和帖子,那么您不需要提供ID,因此我删除了它们。如果需要,您可以重新添加它们。

答案 1 :(得分:0)

您的人际关系似乎不合适。它应该是这样的:

// Game Model
public function posts()
{
   return $this->hasMany('App\Post');
}

// Post Model
public function console()
{
   return $this->belongsTo('App\Console');
}

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

// Console Model
public function posts()
{
   return $this->hasMany('App\Post');
}

您对帖子的Eloquent查询将是:

$this->model->select(SELECTED_FIELDS)
            ->with(array('game','console'))
            ->get();

其中SELECTED_FIELDS表示您要获取的表字段。