【问题标题】:laravel many to many relation newlaravel 多对多关系新
【发布时间】:2020-03-05 23:39:22
【问题描述】:

我遇到了一个问题。我是 laravel 的新手。我在我的应用程序中创建了多对多关系。但它显示错误。请检查以下代码:

错误

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id' cannot be null (SQL: insert into `category_post` (`category_id`, `created_at`, `post_id`, `updated_at`) values (1, 2019-11-09 17:00:29, ?, 2019-11-09 17:00:29))

发布模型代码:

public function  categories()
{
    return $this->belongsToMany('App\Category')->withTimestamps();
}

类别型号代码

public function posts()
{
    return $this->belongsToMany('App\Post')->withTimestamps();
}

后控制器代码

 public function store(Request $request)
{
    $this->validate($request,[


    ]);

    $image = $request->file('image');
    $slug = str_slug($request->name);

    if(isset($image))
    {
        $imageName = $slug.'-'.time().uniqid().'.'.$image->getClientOriginalExtension();

        if(!Storage::disk('public')->exists('posts/'))
        {
            Storage::disk('public')->makeDirectory('posts/');
        }
        $postImage = Image::make($image)->resize(1600,1066)->stream();

        Storage::disk('public')->put('posts/'.$imageName,$postImage);
    }else{

        $imageName = 'default.png';
    }



    $posts = new Post();

    $posts->user_id =Auth::id();

    $posts->title = $request->title;
    $posts->slug = $slug;
    $posts->body = $request->body;
    $posts->image = $imageName;

    $posts->categories()->attach($request->categories);
    $posts->tags()->attach($request->tags);

    $posts->is_approved = true;
    if(isset($request->status))
    {
        $posts->status = true;
    }else{

        $posts->status = false;
    }



    $posts->save();

  //  $posts->tags()->attach($request->tags);
    Toastr::success('Post Is created successfully','Success');
    return redirect()->route('admin.posts.index');

}

我的 create.blde.php 文件代码正常,所有请求都正常进行,但在我提交帖子时显示上述错误..提前致谢

【问题讨论】:

    标签: php laravel eloquent many-to-many


    【解决方案1】:

    帖子和类别之间存在belongs to many关系。为了在您的数据透视表上创建该关系,您必须有一个category_id 和一个post_id。

    代码中的这一行:

     $posts->categories()->attach($request->categories);
    

    是正确的,但您试图将类别附加到 post 对象之前保存它。因此,未保存的 post 对象还没有id。

    保存您的帖子,然后使用您已经编写的attach() 方法附加类别。

    您的tags() 附件也是如此。保存 post 对象后将其粘贴。

    【讨论】:

      猜你喜欢
      • 2014-09-02
      • 1970-01-01
      • 2018-06-15
      • 2018-01-22
      • 2016-02-26
      • 2016-01-04
      • 2018-07-04
      • 1970-01-01
      相关资源
      最近更新 更多