简体   繁体   中英

Laravel eloquent insert data with relationship

I have two models: trainers and trainerClubs. And I have json array. Each json array have a other array.When a json comes to me, I want to add them to the relationship models at the same time. for example; Trainer::insert($request->all());

my json example;

[
    {
        "identity_no": "111222333",
        "first_name": "john",
        "last_name": "doe",
        "TrainerClubs": [
            {
                "club_id": 1,
                "work_type": 1
            },
            {
                "club_id": 2,
                "work_type": 1
            }
        ]
    },
    {
        "identity_no": "444555666",
        "first_name": "jane",
        "last_name": "doe",
        "TrainerClubs": [
            {
                "club_id": 1,
                "work_type": 3
            },
            {
                "club_id": 13,
                "work_type": 3
            }
        ]
    }
]

and my models;

class Trainer extends Model
{
    public $timestamps = true;

    protected $guarded = ['id'];

    public function TrainerClubs()
    {
        return $this->hasMany('App\Modules\Trainer\Models\TrainerClub', 'trainer_id');
    }
}
class TrainerClub extends Model
{
    protected $guarded = ['id','created_at','updated_at'];

    public function Trainer()
    {
        return $this->belongsTo('App\Modules\Trainer\Models\Trainer');
    }
}

my current working code;

    public function create(array $data)
    {
        foreach ($data as $trainer) {
            $crrTrainer = (array)$trainer;
            $clubs = array_pop($crrTrainer);
            $addedTrainer = Trainer::create($crrTrainer);
            foreach ($clubs as $trainerClub) {
                $addedTrainer->TrainerClubs()->create($trainerClub);
            }
        }
        return true;
    }

Thanks for help

Short answer is, you can't save both model at the same time. In your case you have to create first the Trainer:

 $addedTrainer = Trainer::create($crrTrainer);

Later insert the clubs. What you can do different is to create all the clubs at the same time without having to loop through them using createMany :

$addedTrainer->TrainerClubs()->createMany($clubs);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM