【问题标题】:How to save many to many relationships?如何挽救多对多关系?
【发布时间】:2014-01-10 21:34:28
【问题描述】:

我正在为使用 Laravel4 开发的网站创建后台。到目前为止一切顺利,但是当我尝试保存与另一个模型(代码)具有belongsToMany 关系的模型(组件)时遇到了这个错误。

我收到此错误:

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

这是我的创建刀片模板:

@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

还有我的商店功能:

$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();

我不明白。它不应该知道它正在创建的组件的 ID 并简单地将“code_id”关联到数据透视表吗?为什么它要求一个甚至还不存在的“component_id”?

【问题讨论】:

标签: php laravel laravel-4


【解决方案1】:

使用数据透视表时,关系两侧的两个模型都需要已经存在于您的数据库中。

您需要做的就是先将$component 模型保存到您的数据库中,然后您可以与它建立attachsync 关系。

更改以下内容;

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

到;

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

【讨论】:

  • 哦,有道理。谢谢!
猜你喜欢
  • 2015-05-19
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
  • 2017-08-25
  • 2013-01-18
  • 1970-01-01
  • 1970-01-01
  • 2013-03-08
相关资源
最近更新 更多