前提・実現したいこと
Laravel5.8を使用して、ニュース記事、それに意見を投稿するYahooニュースのようなWebサイトを作りたいです。
ニュース記事(article)に、意見(post)をforeignキーで関連づけていけるようにしたいのですが、
ニュース記事に対しての投稿がテスト投稿でうまくいきません。
idは
articles Tableの方に主キーidと、
posts Tableの方にid, article_id, user_id(user_idは後ほど関連づける予定)、その他をつけています
エラーメッセージの指摘通り、
article_idとuser_idはnot nullにはせず、主キーと同じく自動連番でつけたいと考えています。
初心者質問で申し訳ありませんが、どなたかご教示いただけませんでしょうか。
発生している問題・エラーメッセージ
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'article_id' cannot be null (SQL: insert into `posts` (`content`, `article_id`, `user_id`, `updated_at`, `created_at`) values (てすと, ?, ?, 2019-05-08 17:39:50, 2019-05-08 17:39:50))
PHP Laravel articles Table
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAirticlesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('articles', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('content'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('articles'); } }
posts table
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->integer('article_id')->unsigned(); $table->integer('user_id')->unsigned(); $table->text('content'); $table->timestamps(); $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('posts'); } }
Article model
<?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Post; class Article extends Model { protected $fillable=[ 'title','content' ]; public function posts(){ return $this->hasMany('App\Post'); } }
###Post Model
<?php namespace App; use Illuminate\Database\Eloquent\Model; use App\Article; class Post extends Model { protected $fillable = [ 'article_id','user_id','content' ]; public function articles(){ return $this->belongsTo('App\Article'); } }
試したこと
テスト投稿する前に、Seederを使ってテストデータを挿入しようとしたのですが、
General error: 1364 Field ‘article_id’ doesn’t have a default value
とエラーが出てきて、データが挿入できず、手入力を試してみました。
MigrationのTableの設定ができていないのではないかと思いますが、何が悪いのかどうしてもわかりません。
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2019/05/08 10:50