我想在tags表以及post_tag表中插入标签从post创建页面。当我创建一个新的帖子标签插入标签表,但不插入在post_tag表。显示无效的日期时间格式。
SQLSTATE[22007]: Invalid datetime format: 1366不正确的整数值:'start,tas'。(SQL: insert into post_tag (post_id, tag_id) values (20, start,tas))
<>前//存储公共函数storeNewPost(请求请求美元){//返回请求-> ();请求->验证(['post_title' => 'required','post_details' => 'required','category_id' => 'required','image' => 'image|max:15360|dimensions:max_width=4000,max_height=3000']);$image = $request->file('post_thumbnail');$ name_gen =函数()。"。"。图像-> getClientOriginalExtension ();图片::使(图片)->调整(700400)->保存("前端/资产/图片/post/"。name_gen美元);$ save_url ="前端/资产/图片/post/"。name_gen美元;$post = post::create(['user_id' => Auth::id(),"post_uper_title"=>请求-> post_uper_title,"post_title"=>请求-> post_title,"postrongub_title"=>请求-> postrongub_title,"post_details"=>请求-> post_details,"postronglug"=>。大小写不敏感 (' ', '-', $ 请求-> post_title),"seo_title"=>请求-> seo_title,"seo_descp"=>请求-> seo_descp,"铅"=> $请求->领先,"lead2"=>请求-> lead2,"特色"=>请求->特色,"repoter_name"=>请求-> repoter_name,"division_id"=>请求->division_id,"district_id"=>请求-> district_id,"category_id添加"=>请求-> category_id添加,"post_thumbnail"=> save_url美元,"thumbnail_caption"=>请求-> thumbnail_caption,"thumbnail_alt"=>请求-> thumbnail_alt,'created_at' => Carbon::now(),]);如果($){$tags = explosion (",", implode($request->tags));$tagNames = [];If (!empty($tags)) {foreach ($tags as $tagName){$tag = Tags::firstOrCreate(['name'=>$tagName]);如果标签($){$tagNames[] = $tag->id;}}}post ->标记()->同步(请求->标签);$notification = array("消息"=>"后插入成功",'alert-type' => 'success'(;返回重定向()->路线(all.posts) ->($通知);其他}{返回();}}//结束插入post**这是我的标签表**
public function up(){Schema::create('tags', function (Blueprint $table) {表-> bigIncrements("id");表->字符串("名字");表->字符串("鼻涕虫")-> nullable ();表->量变(描述)-> nullable ();表->量变(tag_thumb) -> nullable ();表->文本(thumb_caption) -> nullable ();表->文本(thumb_alt) -> nullable ();表-> softDeletes ();表->时间戳();}(;}
**这是我的Post_tag表**
public function up(){Schema::create('post_tag', function (Blueprint $table) {表->增量("id");表-> unsignedBigInteger (post_id) -> nullable ();表->外国(post_id) ->引用(id) ->("文章")——> onDelete("级联");表-> unsignedBigInteger (tag_id) -> nullable ();表->外国(tag_id) ->引用(id) ->("标记")——> onDelete("级联");表->时间戳();}(;}
我认为你需要使用$tagNames
数组而不是$request->tags
同步:
$post->tags()->sync($tagNames);
根据Laravel文档,sync()
方法需要一个id数组:https://laravel.com/docs/8.x/eloquent-relationships syncing-associations
如果你在你的模型中有许多关系,在你的控制器中使用sync()
方法更新函数。
示例:$post->tags()->sync($request->tags)
;
如果你需要更多的帮助,告诉我。