質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Framework

Frameworkは、アプリケーションソフトを開発する際に、一般的な機能をより簡単に、より早く完了させる事を目的とした、ソフトウェアやライブラリのセットを指します。開発にフレームワークを使用する事で、追加で必要となる機能だけを開発するだけで済む為、開発効率の向上が見込めます。

Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

Q&A

解決済

1回答

1165閲覧

複数テーブルへデータ挿入時にGeneral error: 1364 Field 'name' doesn't have a default valueというエラーに悩まされています。

m.kk

総合スコア23

Framework

Frameworkは、アプリケーションソフトを開発する際に、一般的な機能をより簡単に、より早く完了させる事を目的とした、ソフトウェアやライブラリのセットを指します。開発にフレームワークを使用する事で、追加で必要となる機能だけを開発するだけで済む為、開発効率の向上が見込めます。

Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

PHP

PHPは、Webサイト構築に特化して開発されたプログラミング言語です。大きな特徴のひとつは、HTMLに直接プログラムを埋め込むことができるという点です。PHPを用いることで、HTMLを動的コンテンツとして出力できます。HTMLがそのままブラウザに表示されるのに対し、PHPプログラムはサーバ側で実行された結果がブラウザに表示されるため、PHPスクリプトは「サーバサイドスクリプト」と呼ばれています。

0グッド

0クリップ

投稿2020/07/13 05:59

Laravel Framework 7.19.1 を使っております。

やりたいこと
データ登録時に同時に他テーブルにも同時に登録したい。

具体的にいうと
bookデータ登録時に一緒にtagデータも挿入したい。
下記にコードを貼らせていただきます。

BookController public function store(Request $request, Book $book, Tag $tag) { // dd($request->all()); $user = auth()->user(); $file_name = $request->file('book_image')->getClientOriginalName(); $request->file('book_image')->storeAs('public',$file_name); $data = $request->all(); $validator = Validator::make($data,[ 'title' => ['string', 'max:30'], 'over_view' => ['string', 'max:20480'], 'book_image' => ['file', 'image', 'mimes:jpeg,png,jpg', 'max:20480'] ]); $validator->validate(); $book = new Book; $book->bookStore($user->id, $data); $book->save(); // dd($book); $data = []; if(isset($data["tags"])) { $tag->tagStore($data["tags"]); $tag_ids = $tag->getTagIds($data["tags"]); $book->bookTagSync($tag_ids); } $tag->save(); return redirect('/books')->with('success', '投稿が完了しました。'); }
BookModels public function tags() { return $this->belongsToMany(Tag::class); } public function bookStore(Int $user_id, Array $data) { //本登録項目をmodelにまとめcontrollerの記述を少なく $this->user_id = $user_id; $this->book_image = $data['book_image']; $this->title = $data['title']; $this->over_view = $data['over_view']; // $this->status = $data['book_status_id']; $this->save(); return; } public function getEditBook(Int $user_id, Int $id) { return $this->where('user_id', $user_id)->where('id', $id)->first(); } public function bookUpdate(Int $book_id, Array $data) { $this->id = $book_id; $this->title = $data['title']; $this->over_view = $data['over_view']; // $this->status = $data['book_status_id']; $this->update(); return; } public function bookDestroy(Int $user_id, Int $book_id) { return $this->where('user_id',$user_id)->where('id',$book_id)->delete(); } //タグ public function bookTagStore(Array $tag_ids){ foreach($tag_ids as $tag_id) { $this->tags()->attach($tag_id); } } public function bookTagSync(Array $tag_ids){ //同期 $this->tags()->sync($tag_ids); }
tagModels class Tag extends Model { public $timestamps = false; public function books() { return $this->belongsToMany(Book::class, 'book_tag', 'tag_id', 'book_id'); } public function tagStore(Array $_tag_names){ //タグがすでにあるかの判定 $this->name = $_tag_names['name']; if(!empty($_tag_names)){ //タグがあるかforeachで探す.['name' => $tag_name] foreach($_tag_names as $tag_name){ $tag_names[] = ['name' => $tag_name]; } //insertOrIgnoreであれば無視、なければ挿入 DB::table('tags') ->where('name','') ->insertOrIgnore($tag_names); } } public function getTagIds($tag_names){ foreach($tag_names as $tag_name){ //idから名前を1から取り出して$tag_idに代入 $tag_id = $this::select('id')->where("name",$tag_name)->first(); //$tag_ids[]を作成してidを全て代入 $tag_ids[] = $tag_id->id; } return $tag_ids; } public function getPopularTags(){ //withCountでレコード数をとる //0で公開しているbooksのデータを呼び出し $popular_tags = $this::withCount([ 'books' => function($query) { $query->where('status',0); }]) ->orderBy('books_count', 'desc') ->take(5) ->get(); return $popular_tags; } }
view @extends('layouts.app') @section('content') <form action="{{ route('books.store') }}" method="POST" enctype="multipart/form-data"> @csrf <input type="text" name="title" placeholder="タイトル" class="form-control form-control-lg"> <textarea rows="8" cols="40" type="textarea" name="over_view" placeholder="概要" class="form-control form-control-lg"></textarea> <input type="file" id="book_image" name="book_image" > <div class="p-postEdit-form__input-tags"> @for ($i = 1; $i <= 5; $i++) <input type="text" name="tags[]" class="p-postEdit-form__input-tag @error('tags[]'.$i) is-error @enderror" value="{{ old('tags[]'.$i) }}" placeholder="#タグ"> @error('tags[]'.$i) <span class="p-postEdit-form__errorMsg" role="alert"> <strong>{{ $message }}</strong> </span> @enderror @endfor </div> <input type="submit" value="Submit"></button> </form> @endsection
DB class CreateBooksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('books', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('user_id')->comment('ユーザーID'); $table->string('book_image')->comment('画像'); $table->string('title'); $table->text('over_view')->comment('概要'); $table->unsignedSmallInteger('status')->default(0)->comment('0:公開,1:非公開'); $table->timestamps(); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade') ->onUpdate('cascade'); }); } class CreateTagsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tags', function (Blueprint $table) { $table->increments('id'); $table->string('name')->unique()->comment('カテゴリー名'); }); } class CreateBookTagTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('book_tag', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedInteger('book_id')->comment('本ID'); $table->unsignedInteger('tag_id')->comment('カテゴリーID'); $table->foreign('book_id')->references('id')->on('books')->onDelete('cascade'); $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade'); $table->unique([ 'book_id', 'tag_id' ]); }); }

中間テーブルも指定して
->insertOrIgnore($tag_names);でカラムは指定しているので入ると思っているのですが、うまくいかなく質問させていただきます。
どうぞよろしくお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

できました!
コントローラの順番がおかしかったです。

投稿2020/07/14 00:18

m.kk

総合スコア23

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問