这是一个例子
表结构
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');
}
}
我需要获取某个帖子的游戏名称。如何使用 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。 其次,关系返回值必须改变。在hasOne和belongsTo中,您将需要使用如下所示的模型类名称。我还遗漏了一些可选代码,这些代码对于代码工作来说不是必需的。
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
获取游戏名称
关于php - Laravel 获取外部表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29383845/