現金出納簿5 テーブルsub_categories

テーブルsub_categoriesまわりのプログラムを作る。ここからは今までの内容をコピペしながら進む。

php artisan make:migration create_sub_categories_table

カラム名に気を付ける。(半角スペース等)

        Schema::create('sub_categories', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('category_id') ;
            $table->tinyInteger('sub_category_number');
            $table->string('sub_category_name', 50);
            $table->timestamp('updated_at')->useCurrent()->nullable();
            $table->timestamp('created_at')->useCurrent()->nullable();
        });
php artisan migrate
php artisan make:model SubCategory
php artisan make:controller SubCategoryController --resource
use App\Http\Controllers\SubCategoryController;

Route::resource('subcategories', SubCategoryController::class);

ルーティング情報を確認。

php artisan route:list

「1対多」の「多」側 → メソッド名は複数形、 1対 多 の1側は単数形、従テーブルには「1対1」「1対多」関わらず belongsTo() メソッドを定義。

    protected $fillable = [
        'category_id',
        'sub_category_number',
        'sub_category_name'
    ];

    public function category()
    {
       return $this->belongsTo('App\Models\Category');
    }
    public function subcategories()
    {
       return $this->hasMany('App\Models\SubCategory');
    }  
use App\Models\SubCategory;//追記

    public function index()
    {
        $subcategories = SubCategory::with(['category.type'])->get(); 
        $categories = Category::with('type')->get();
         
        return view('subcategories.index',compact('subcategories','categories')); 
    }

コメント