【发布时间】: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