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

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

新規登録して質問してみよう
ただいま回答率
85.49%
Laravel 5

Laravel 5は、PHPフレームワークLaravelの最新バージョンで、2014年11月に発表予定です。ディレクトリ構造がが現行版より大幅に変更されるほか、メソッドインジェクションやFormRequestの利用が可能になります。

Q&A

解決済

1回答

1133閲覧

【Laravel】一対多アソーシエーション・MAMP環境でmysqlへ接続したい

Airi.

総合スコア8

Laravel 5

Laravel 5は、PHPフレームワークLaravelの最新バージョンで、2014年11月に発表予定です。ディレクトリ構造がが現行版より大幅に変更されるほか、メソッドインジェクションやFormRequestの利用が可能になります。

0グッド

0クリップ

投稿2021/02/08 09:15

編集2021/02/08 10:00

一対多のアソーシエーションを組むためのmigrationfileを作成したいのですが、エラーが発生し、解決ができません。

【補足】UserテーブルのIDをRecipeテーブルの【user_id】カラムへ保存したいと考えております。

エラー内容

Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `recipes` add constraint `recipes_user_id_foreign` foreign key (`user_id`) references `users` (`id`) on delete cascade) at /Applications/MAMP/htdocs/test1/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664 660| // If an exception occurs when attempting to run a query, we'll format the error 661| // message to include the bindings with SQL, which will make this exception a 662| // lot more helpful to the developer instead of just the database's errors. 663| catch (Exception $e) { > 664| throw new QueryException( 665| $query, $this->prepareBindings($bindings), $e 666| ); 667| } 668| Exception trace: 1 PDOException::("SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint") /Applications/MAMP/htdocs/test1/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458 2 PDOStatement::execute() /Applications/MAMP/htdocs/test1/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458

Recipeの migrationfile の記述

//2021_02_07_060223_create_recipes_table.php class CreateRecipesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('recipes', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedInteger('user_id'); //カラム追加 $table->foreign('user_id') //外部キー制約 ->references('id')->on('users') //usersテーブルのidを参照する ->onDelete('cascade'); //ユーザーが削除されたら紐付くpostsも削除 $table->string('title'); $table->unsignedBigInteger('category_id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('recipes'); } }

Usermigrationfile

class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('profile'); $table->string('image'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }

##仮説と仮説を確認するための問題点

仮説 :
参照元, 参照先のキーの型が異なったために発生したエラーの可能性があるため、キーを見比べて異なるようであれば、キーを変更する必要がある。 参考サイト

問題 :
MAMP環境でmysqlのテーブルを確認する方法がわからない

$ mysql -u root //mysqlへ接続 mysql> show create table users \G; ERROR 1046 (3D000): No database selected ERROR: No query specified mysql> SHOW DATABASES; // test1というデータベースがない。 mysql> USE test1; ERROR 1049 (42000): Unknown database 'test1'

データベース

test1という名前で存在していますが、ターミナルからは確認ができません。
おそらくMAMP環境を用いているためかと思います。

イメージ説明

どのような手順で問題を解決すれば良いかアドバイスをいただきたいです。
また、もっといい方法があれば、ご教授いただけますと幸いです。どうぞよろしくお願いいたします。

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

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

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

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

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

m.ts10806

2021/02/08 09:33

MySQL自体複数入ってるということはないですか?
Airi.

2021/02/08 10:06

mysqlを複数入れられるということを知らなかったのですが、複数入れているということはないと思います。もし、複数入っているとすれば、ローカル環境とMAMPの両方にmysqlが入っているのかもしれません。 MAMP自体もローカルのmysqlを利用しているのか、MAMP環境そのものにmysqlがあってそのmysqlを利用しているのかもよく理解ができていません。。 質問の回答になっておらず申し訳ありません><
guest

回答1

0

ベストアンサー

エラーを解消するためには、user_idカラムの型をUNSIGNED BIGINTにするとどうでしょうか。

CreateRecipesTable クラス

php

1$table->unsignedBigInteger('user_id');

usersテーブルのidカラムにはbigIncrementsメソッドが使用されており、UNSIGNED BIGINTになっていると思われるためです。

参考: 利用可能なカラムタイプ

MySQLについては、他の方のご指摘通り、複数インストールされているのではないでしょうか。
例えば、Homebrewなどでもインストールした可能性があると思います。

mysqlコマンドを絶対パスで指定すると、MAMPのmysqlコマンドを起動できないでしょうか。

例:

$ /Applications/MAMP/Library/bin/mysql -u root //mysqlへ接続

(パスはMAMPのインストール先によって異なります)

投稿2021/02/08 15:39

編集2021/02/09 00:41
Lulucom

総合スコア1899

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

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

Airi.

2021/02/09 01:05 編集

回答ありがとうございます! 上手くいきました! Lulucomさんからいただいた内容と別の方から教えていただいた以下の記事を参考に 型別でmigrationを実行しました! 参考記事:https://qiita.com/0w0/items/4a9cb7d27794bfb93d46 1)【User】bigIncrements('id') 【Recipe】unsignedBigInteger('user_id'); 2)【User】increments('id')  【Recipe】integer(user_id) 対になる型を探し出して変更すればよかったのですね! 参考のカラムタイプについてもありがとうございます!!! 今後、公式サイトにも情報収集を行う意識づけをしていきたいと思いますm(_ _)m 1)【User】bigIncrements('id') 【Recipe】unsignedBigInteger('user_id'); ```Recipe public function up() { Schema::create('recipes', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');; $table->string('title'); $table->unsignedBigInteger('category_id'); $table->unique(['user_id'],'uq_roles'); $table->timestamps(); }); } ``` ```User public function up() { Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('profile'); $table->string('image'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } ``` 2)【User】increments('id')  【Recipe】integer(user_id) ```Recipe public function up() { Schema::create('recipes', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');; $table->string('title'); $table->unsignedBigInteger('category_id'); $table->unique(['user_id'],'uq_roles'); $table->timestamps(); }); } ``` ```User public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('profile'); $table->string('image'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } ``` また、Mysqlの件もありがとうございます! ダウンロードされている場所を探し出して絶対パスで試してみます!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.49%

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

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

質問する

関連した質問