LoginSignup
1
0

More than 3 years have passed since last update.

【MySQL】データのINSERT

Posted at

 Laravelでのアプリ制作中に、投稿機能が動作しなくなってしまいました。
 他の機能は正しく動作するか調べる為に、以下の条件でMySQLにデータをINSERTする方法を調べましたので、アウトプットしていきます。

 ※ 今回は、以下の記事を参考にさせて頂きました:relaxed::tulip:
http://www.hiihah.info/index.php?E71%EF%BC%9AMySQL%E3%81%A7%E3%81%AE%E6%97%A5%E4%BB%98%E3%80%81%E6%99%82%E5%88%BB%E3%81%AE%E3%82%A4%E3%83%B3%E3%82%B5%E3%83%BC%E3%83%88%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6

 テーブル構成

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->text('body');
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

 articlesテーブルは、上記の通り

・id
・title
・body
・user_id
・created_at
・updated_at

 の6つのカラムで構成されています。

 これにデータをINSERTするには、以下のコマンドを実行します。

INSERT INTO articles VALUES(null, 'タイトル名', '記事の内容', 'ユーザーID', cast('年-月-日' as date), null);

 上記だと作成時刻が0:00になりますので、時刻の指定をする場合は、以下のコマンドを実行します。

INSERT INTO articles VALUES(null, 'タイトル名', '記事の内容', 'ユーザーID', cast('年-月-日 ○:○○' as datetime), null);

 これで以下のようにINSERTすることができました。

+----+-----------------+-----------------+---------+---------------------+---------------------+
| id | title           | body            | user_id | created_at          | updated_at          |
+----+-----------------+-----------------+---------+---------------------+---------------------+
|  4 | タイトル名        | 記事の内容        |       1 | 2021-02-14 11:56:00 | NULL                |
+----+-----------------+-----------------+---------+---------------------+---------------------+
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0