简体   繁体   中英

How to save many to many relationships?

I am creating the backoffice for a website I'm developing with Laravel4. So far so good, but I got into this error when trying to save a model (components) that has a belongsToMany relationship with another model (codes).

I am getting this error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'component_id' cannot be null (SQL: insert into `component_codes` (`code_id`, `component_id`) values (4, ))

Here's my create blade template:

@foreach ($codes as $code)
    <tr>
        <td>{{ $code->id }}</td>
        <td>{{ $code->code }}</td>
        <td>{{ $code->packing }}</td>
        <td>@if ($code->active == 1) <span class="label label-success">Active</span> @else <span class="label label-secondary">Inactive</span> @endif</td>
        <td><input type="checkbox" name="code_checkbox[]" value="{{ $code->id }}" /></td>
    </tr>   
@endforeach

And my store function:

$component            = new PackbuilderComponent;
$component->name_en   = Input::get('name_en');
$component->filter_id = Input::get('filter_id');
$component->image     = $fullpath;
$component->thumb     = $fullthumbpath;
$component->codes()->sync(Input::get('code_checkbox'));
$component->save();

I don't get it. Isn't it supposed to know the ID of the component it's creating and simply associate the "code_id" to the pivot table? Why is it asking for a "component_id" that doesn't even exist yet?

When working with the pivot table, both models on either side of the relationship need to already exist in your database.

All you need to do is save the $component model to your database first, then you can attach or sync relationships to it.

Change the following;

$component->codes()->sync(Input::get('code_checkbox'));
$component->save();

To;

$component->save();
$component->codes()->sync(Input::get('code_checkbox'));

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