rarala2020
@rarala2020 (ら らら)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

Laravelで1回のsubmitで親子関係の2テーブルに同時にデータを登録する方法

Larabel6を利用し、1タイトル内に3つまで商品登録できる投稿フォームを作成しています。

DBは下記のように「post_id」を外部キーとしてつないだ1:多の2テーブル構造になっており、
親テーブルのカラムにデータを保存するところまでは出来たのですが、
子テーブルにカラムのある商品情報データを同時に登録させる方法が分からず困っています。

モデルにリレーションの記述はしてみたのですが、
このほかにどのファイルをどのように書き換えれば
1度のsubmitでそれぞれのテーブルにデータを保存できますでしょうか。

Laravelも始めたばかりであまり理解ができておらず、
初心者質問で恐縮ですがよろしくお願い致します。

投稿フォーム

title =>

商品1(item_no=>1)
img =>
url =>
price =>

商品3(item_no=>2)
img =>
url =>
price =>

商品3(item_no=>3)
img =>
url =>
price =>

postsテーブル(親)

id
title
timestamp

itemsテーブル(子)

id
post_id ★FK
item_no
img
url
price
timestamp

モデル

app>Http>Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
    protected $guarded = ["id"];    
    public function items() {
    return $this->hasMany('App\Item');
    }
}
app>Http>Item.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Item extends Model
{
    protected $guarded = ["id"];

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

マイグレーション

migrations>posts_table.php
                public function up()
                {
                    Schema::create("posts", function (Blueprint $table) {
                        $table->increments('id');
                        $table->string('title',255)->nullable();
                        $table->timestamps();
                    });
                }
migrations>items_table.php
                public function up()
                {
                    Schema::create("items", function (Blueprint $table) {
                        $table->increments('id');
                        $table->integer('post_id')->unsigned();
                        $table->integer('item_no')->nullable();
                        $table->text('img')->nullable();
                        $table->text('url')->nullable();
                        $table->integer('price')->nullable();
                        $table->timestamps();
                    });
                }

コントローラー

PostsController.php
public function index(Request $request)
        {
            $keyword = $request->get("search");
            $perPage = 25;

            if (!empty($keyword)) {
                $post = DB::table("posts")
                ->orWhere("posts.title", "LIKE", "%$keyword%")->select("*")->addSelect("posts.id")->paginate($perPage);
                $post = DB::table("posts")
                ->select("*")->addSelect("posts.id")->paginate($perPage);              
            }          
            return view("post.index", compact("post"));
        }

        public function create()
        {
            return view("post.create");
        }


        public function store(Request $request)
        {
            $this->validate($request, [
                "title" => "nullable|max:255", //string('title',255)->nullable()
            ]);
            $requestData = $request->all();            
            Post::create($requestData);    
            return redirect("post")->with("flash_message", "post added!");
        }
ItemsController.php
        public function index(Request $request)
        {
            $keyword = $request->get("search");
            $perPage = 25;

            if (!empty($keyword)) {
                $item = DB::table("items")
                ->leftJoin("posts","posts.id", "=", "items.post_id")
                ->orWhere("items.post_id", "LIKE", "%$keyword%")->orWhere("items.item_no", "LIKE", "%$keyword%")->orWhere("items.img", "LIKE", "%$keyword%")->orWhere("items.url", "LIKE", "%$keyword%")->orWhere("items.price", "LIKE", "%$keyword%")->orWhere("posts.title", "LIKE", "%$keyword%")->select("*")->addSelect("items.id")->paginate($perPage);
            } else {
                $item = DB::table("items")
                ->leftJoin("posts","posts.id", "=", "items.post_id")
                ->select("*")->addSelect("items.id")->paginate($perPage);              
            }          
            return view("item.index", compact("item"));
        }

        public function create()
        {
            return view("item.create");
        }

        public function store(Request $request)
        {
            $this->validate($request, [
                "post_id" => "required|integer", //integer('post_id')
                "item_no" => "nullable|integer", //integer('item_no')->nullable()
                "img" => "nullable", //text('img')->nullable()
                "url" => "nullable", //text('url')->nullable()
                "price" => "nullable|integer", //integer('price')->nullable()
            ]);
            $requestData = $request->all();            
            Item::create($requestData);    
            return redirect("post")->with("flash_message", "item added!");
        }

投稿フォーム(post/create.blade.php)

<form method="POST" action="/post/store" class="form-horizontal">
{{ csrf_field() }}
<input class="form-control" name="title" type="text" id="title" value="{{old('title')}}">
<input class="form-control" name="item_no" type="text" id="item_no" value="1">
<input class="form-control" name="url" type="text" id="url" value="{{old('url')}}">
<input class="form-control" name="price" type="text" id="price" value="{{old('price')}}">
<!--商品2,3は省略-->
<input class="btn btn-primary" type="submit" value="Create">
</form>

0

No Answers yet.

Your answer might help someone💌