我正在使用$hidden
和$appends
从json数组中隐藏pivot
关键字,并将对象拉入主数组。在游戏模型中,我在脚本下方添加了执行上述功能的功能
protected $hidden = ['pivot'];
protected $appends = ['user_id','highscore', 'level'];
public function getUserIdAttribute()
{
return $this->pivot->user_id;
}
public function getHighScoreAttribute()
{
return $this->pivot->highscore;
}
public function getLevelAttribute()
{
return $this->pivot->level;
}
现在的问题是,我想获取所有游戏,而且我知道它是如此简单,我只是将其添加到脚本下面的控制器中
$Games = Game::all();
return new GameResource($Games); /* GameResource is for API */
但是这个将以上脚本添加到模型中后,这是返回以下错误。
ErrorException: Trying to get property user_id of non-object
任何人都可以指导我如何同时管理这两项功能,因为我需要这两项。如果有人能提供帮助,我将不胜感激。
@emix评论后
@emix它不是重复的,因为参考是关于核心php的,而我正在使用laravel。当然,laravel是用php构建的,但是结构仍然很复杂,所以我认为这与您所引用的不一样
答案 0 :(得分:0)
仅当您通过多对多关系(BelongsToMany)获取模型时,枢轴才可用。数据透视表代表数据透视表上的字段(例如games_users),并因此表示针对该特定关系存在的字段。
当您直接从游戏模型(又称为游戏表)中提取数据时,就没有关系或数据透视表来提取数据。