【问题标题】:Cannot add or update a child row laravel 5.4 many to many relation无法添加或更新子行 laravel 5.4 多对多关系
【发布时间】:2018-07-16 16:43:00
【问题描述】:

在多对多加入中我得到这个错误:

SQLSTATE[23000]:违反完整性约束:1452 无法添加或 更新子行:外键约束失败 (laravel.posts_tag, 约束posts_tag_tag_id_foreign FOREIGN KEY (Tag_ID) REFERENCES Tag (ID) ON DELETE CASCADE) (SQL: insert 转化为Posts_Tag (Posts_ID, Tag_ID) 值 (26, Tag num 2))

我的控制器:

public function Share(Request $request)
{

    $posts = Posts::create($request->all());

    $posts->tags()->attach(Input::get('Tag'));

    return $posts;

    return Redirect()->back();

}

我的模型:

public function tags()
{
    return $this->belongsToMany('App\Tag', 'Posts_Tag', 'Posts_ID', 'Tag_ID');
}

查看:

            {{ Form::open(array('url'=>'post')) }}

            {{ Form::label('Title') }} : {{ Form::text('Title') }}
            <br>
            {{ Form::label('Content') }} : {{ Form::textarea('Content') }}
            <br>
            {{ Form::label('Tag :') }}
            <select name="Tag" id="Tag" class="Tag">
                @foreach($tag as $tag)
                    <option>{{ $tag->Tag }}</option>
                @endforeach
            </select>
            <br>
            {{ Form::submit('Share Post') }}

            {{ Form::close() }}

【问题讨论】:

  • 请注意大写和语法。

标签: php laravel


【解决方案1】:

因为你没有传递任何标签id,所以填写选项的值

<select name="tags" id="Tag" class="Tag">
                //tags is a better name for collection of tgas
       @foreach($tags as $tag)
              <option value='{{$tag->id}}'>{{ $tag->Tag }}</option>
       @endforeach
</select>

在你的控制器中

$post->tags()->attach($request->tags);

【讨论】:

    【解决方案2】:

    attach() 不能使用实际的标签名称。因为您传递的是名称而不是 ID,所以您需要先获取标签 ID:

    $post = Posts::create($request->all());
    $tagId = Tag::where('name', $request->tag)->value('id');
    $post->tags()->attach(tagId);
    

    【讨论】:

      猜你喜欢
      • 2020-05-11
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      • 1970-01-01
      • 2017-03-20
      • 2017-11-08
      • 1970-01-01
      • 2019-06-20
      相关资源
      最近更新 更多