dongye3917 2018-03-01 15:36
浏览 22
已采纳

从包括子模型的DB中获取雄辩的模型

I'm learning PHP and the Laravel framework and i'm getting stuck on loading some data from the database.

I have 2 models, Game and Player

Player model (curently empty):

class Player extends Model
{
}

Game model:

class Game extends Model
{
    public $Players = [];

    public function __construct(array $players = [])
    {
        $this->Players = $players;
    }

    public function SaveGame()
    {
        if($this->save()) {
        Log::info("New game created with id " . $this->id);
        }
        foreach ($this->Players as $key => $player){
            if ($this->Players()->save($player)){
            Log::info("player added to game with id " . $player->id);
            }
        }
    }

    static function GetGame($gameId)
    {
        Return Game::find($gameId);
    }

    public function Players()
    {
        return $this->hasMany(Player::class );
    }
}

And i have a GameController:

class GameController extends Controller
{
   public function create()
    {
        $players = [];
        for ($i = 1; $i <= 3; $i++) {
            $player = new Player();
            array_push($players,$player);
        }

        $game = new Game($players);
        $game->SaveGame();

        return $game;
    }

    public function LoadGame($id)
    {
        $game = Game::GetGame($id);
        return $game;
    }
}

If i call the create() method of my GameController, it creates a game in my Game table and 3 players in the player table with the gameID of the corresponding game so i think the relation works fine.

But if i check the response of the create() method i get only this:

{
"updated_at": "2018-03-01 15:13:37",
"created_at": "2018-03-01 15:13:37",
"id": 3952
}

Also the LoadGame() function returns just the game. Actually i need the game with all its players inside. Something like this:

{
"updated_at": "2018-03-01 15:13:37",
"created_at": "2018-03-01 15:13:37",
"id": 3952,
"players":[
       {"name":"player1"},
       {"name":"player2"},
       {"name":"player3"},
     ],
}

What i'am doing wrong?/How do i get the wished result?

I'm also not sure if the Models are the right place to do the database actions and the controllers are the place to create the objects like i do in the posted code. If my "code structure" is not the best practice, some advice in this is also welcome!

  • 写回答

2条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 写c++代码,第7题说一下使用的计算方法
      • ¥15 postman接口自动化测试报告实践总结
      • ¥15 有关c++的问题,利用相关知识
      • ¥15 求香农编码和解码的matlab代码
      • ¥20 ROS中的TEB局部规划问题
      • ¥20 关于#matlab#的问题:要求测出上面图片中所有同心圆的半径
      • ¥20 epanet软件运行问题
      • ¥15 Python 文件读取
      • ¥60 dpabi进行Alff计算时脑池有干扰信号
      • ¥15 利用kmeans或kshape聚类分析对归一化的无量纲时间-降雨序列进行聚类