Creating new record and relationships in one go

馋奶兔 提交于 2019-12-31 05:57:04

问题


I have the following basic schema:

players

id
name

profiles

id
player_id
email

subsets

id
profile_id
alias

I was under the impression the following operation was possible when creating a new record:

Player::create([
    'name' => 'Player 1',
    'profile.email' => 'player1@email.com',
    'profile.subset.alias' => 'Player 1 alias'
]);

Since this code doesn't seem to work, is there anyway to save relationships records together with the create method?


回答1:


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.



来源:https://stackoverflow.com/questions/23183394/creating-new-record-and-relationships-in-one-go

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!