2016-05-14 70 views
0

表。现在,如果我限制我的结果说前3名(这是我在游戏桌上的所有内容),那么它会运行,但更多的是它会抛出异常......关系错误?Laravel口才关系只返回收效甚微

关系:

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所以实际上倾销$后,我在我的第四入口看到这...这是返回NULL

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

前3个返回值。但是第四个都返回NULL。我又只有3 Games表

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) 

回答

1

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

// 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'); 
} 

如果你的表被命名为游戏机,游戏和职位,分别,那么你不需要提供身份证,所以我把他们赶走。如果需要,您可以重新添加它们。

+0

是刚刚添加特定的名称,以避免任何其他问题。 所以我做了开关,现在运行在我的postTransformer“试图获得非对象的属性”:'游戏'=> $ post-> games-> name, 正在返回的对象是游戏,但... – Citti

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'); 
} 

而且你的口才查询为岗位将是:

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

其中SELECTED_FIELDS意指表字段,你想获取。

+0

所以我做了开关,现在运行到“试图获得非对象的属性”在我的postTransformer:'游戏'=> $ post-> games-> name,被返回的对象是游戏尽管... – Citti