Creating new record and relationships in one go

后端 未结 1 349
庸人自扰
庸人自扰 2021-01-29 04:00

I have the following basic schema:

players

id
name

profiles

id
player_id
email


        
相关标签:
1条回答
  • 2021-01-29 04:17

    Basically, you can't do this as easy as it looks.

    In the docs, all related models are created after the base model is created

    $profile = new Profile(array('email' => 'player1@email.com','alias'=>'Player 1 alias'));
    
    $player = new Player(array('name'=>'Player 1'));
    
    $player = $post->profile()->save($profile);
    

    However , if you really want to do it in one go, you can overwrite the save() method in the Player model :

    public function save(){
            Database::transaction(function() {
                        $profileModel = new Profile($this->profile);
    
                        parent::save();
    
                        $this->profile()->insert($profileModel);
    
                    });
    }
    

    You will then pass the array to the Player method like :

    array(
    name='Player name',
    profile=>array(
             email=>'player1@email.com',
             subset=>array(
               alias=>'Player 1 alias'
              )
    );
    

    Although this is not a recommended action.

    Please read more about how to save the Eloquent models and relationships :

    Tutorial 1 Tutorial 2

    Everywhere is suggested to create the base model first, then the related models.

    0 讨论(0)
提交回复
热议问题