获取外部表值 laravel
Getting foreign tables value laravel
这里有一个例子
Table 结构
Game
--id
--game
Posts
--id
--game_id
--post_text
class Posts extends Eloquent {
protected $primaryKey = 'id';
protected $table = 'posts';
public function games() {
return $this->hasOne('games','id');
}
}
class Games extends Eloquent {
protected $primaryKey = 'id';
protected $table = 'games';
public function posts() {
return $this->belongsTo('posts','game_id');
}
}
我需要获取某个post的游戏名称。我如何使用 eloquent 获取它?
这是我的初始代码
echo $post->games['game'];
但是我得到了错误的数据。
查询方式是这样的
'query' => string 'select * from `games` where `games`.`id` = ? limit 1' (length=52)
'bindings' =>
array (size=1)
0 => int 5
首先Eloquent模型名称不是复数,所以默认应该是Game和Post。
其次必须更改关系 return 值。在 hasOne 和 belongsTo 中,您需要使用模型 class 名称,如下所示。我还遗漏了一些不需要代码运行的可选代码。
class Post extends Eloquent {
public function game() {
return $this->hasOne('Game');
}
}
class Game extends Eloquent {
public function post() {
return $this->belongsTo('Post');
}
}
现在可以通过$post->game->name
获取游戏名称
这里有一个例子
Table 结构
Game
--id
--game
Posts
--id
--game_id
--post_text
class Posts extends Eloquent {
protected $primaryKey = 'id';
protected $table = 'posts';
public function games() {
return $this->hasOne('games','id');
}
}
class Games extends Eloquent {
protected $primaryKey = 'id';
protected $table = 'games';
public function posts() {
return $this->belongsTo('posts','game_id');
}
}
我需要获取某个post的游戏名称。我如何使用 eloquent 获取它?
这是我的初始代码
echo $post->games['game'];
但是我得到了错误的数据。
查询方式是这样的
'query' => string 'select * from `games` where `games`.`id` = ? limit 1' (length=52)
'bindings' =>
array (size=1)
0 => int 5
首先Eloquent模型名称不是复数,所以默认应该是Game和Post。 其次必须更改关系 return 值。在 hasOne 和 belongsTo 中,您需要使用模型 class 名称,如下所示。我还遗漏了一些不需要代码运行的可选代码。
class Post extends Eloquent {
public function game() {
return $this->hasOne('Game');
}
}
class Game extends Eloquent {
public function post() {
return $this->belongsTo('Post');
}
}
现在可以通过$post->game->name