php - Laravel 获取外部表值

标签 php mysql laravel eloquent

这是一个例子

表结构

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/

相关文章:

php - Laravel 仅从关系表获取数据

php - 在 Laravel 中使用 groupby 选择最新的行

php - 切换到从 PHP 编辑 Mysql 数据

php - $new_link 应该在 mysql_connect() 中使用吗?

php - 在后台centos服务器运行php脚本

MySQL 选择对给定行具有特定值的表的 column_names

php - 如何在MySQL数据库中以不同的格式保存数据

php - 无法将 PHP 连接到 bluemix 中的 db2

mysql - 使用对一列的另一个选择查询的结果将数据插入表中

php - 如何在具有多个 foreach 的表单中仅显示 1 个提交按钮