سؤال

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?

هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top