简体   繁体   中英

In Laravel How to insert related models

For example: I have Project model and Need model.
So when the user creates a new project he will have to create it's (needs) also, Which can be more than one per project.
I did this in the projectController's "store" method :-

$project = new Project;
$project->name = $request->project_name;
$project->type = $request->project_type;
// ... etc

if ( $request->exists("project_needs") ) {
    foreach ( $request->project_needs as $project_need ) {
        $need = new Need;
        $need->title = $project_need['title'];
        $need->project_id = $project->id // Here is the thing
    }
}

But it gives me an error because (I think) that the project_id is not created yet, Since it's not saved to the database, So what is the best way to create both models instances (Project & Needs) and save them with their relationship?
Should I save the project and then get the (last-save-id) ? or there is a better (Laravel way) to do that?

Update:-
projects table schema :-
id, name, type_id

needs table schema :-
id, project_id, title

types table schema :-
id, name, description

You need to persist the project to get an id and be able to add related needs.

$project = new Project;
$project->name = $request->project_name;
$project->type = $request->project_type;
// ... etc

$project->save(); // Saving to database;

if ($request->exists("project_needs")) {
    foreach ($request->project_needs as $project_need) {
        $project->needs()->create([
            'title' => $project_need['title'],
        ]);
    }
}

Don't forget to add title to the $fillable on the Need model

Also Project model must define the relationship as one-to-many:

// Project.php

public function needs()
{
    return $this->hasMany(Need::class);
}

Either you can follow this method.

$needs = [
  [
    'title' => 'A new title.',
  ],
  [
    'title' => 'Another new title.',
  ],
];

$project->needs()->createMany($needs);

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