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条回答 默认 最新

  • dsc80135 2018-03-22 11:24
    关注

    Its so easy!, i found the solution by simply experimenting arround as i could not find a solution on the internet.

    In the Game model I removed the

    • constructor (create own constructor in Laravel seems to be not recommended)
    • SaveGame() (save my game in the controller now)
    • GetGame() (useless, can use Game::find(x) in controller)

    In the GameController i changed my create() function a bit. This is the result:

    public function create()
      {
          $game = new Game();          // creates a new game
          $game->Save();               // saves the new game into the db
    
          for ($i = 1; $i <= 3; $i++) {
              $player = new Player();              // creates a new player
              $game->Players()->Save($player);     // stores the player to the game in the db
          }
    }
    

    I also changed my LoadGame() method in my GameController to

    public function LoadGame($id)
    {
        $game = Game::find($id);        // Instead of doing this in a own method in my model 
        $game->players                  // adds the players to the game object for some reason
        return $game;                   // returns the game (as json) incl. all its players
    }
    

    This results in a json string what contains the game vars including a player array with its players. I dont understand why this is working but it is.

    The weird thing is if i exchange $game->players for $game->Players() or $game->Players (like the has many method in the model) it does not work. Maybe someone can explain me why this is? (as i cant find any clarifying documentation to this)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体