简体   繁体   English

如何保存多对多关系?

[英]How to save many to many relationships?

I am creating the backoffice for a website I'm developing with Laravel4. 我正在为我正在使用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). 到目前为止一切都那么好,但是在尝试保存与另一个模型(代码)具有belongsToMany关系的模型(组件)时遇到了这个错误。

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? 是不是应该知道它正在创建的组件的ID,并简单地将“code_id”与数据透视表相关联? Why is it asking for a "component_id" that doesn't even exist yet? 为什么要求一个甚至不存在的“component_id”呢?

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. 您需要做的就是首先将$component模型保存到您的数据库,然后您可以attachsync它的关系。

Change the following; 改变以下内容;

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

To; 至;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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