Relacionamento entre vários Models | Fórum | School of Net

Deseja poder participar de nosso fórum e tirar todas as suas dúvidas?
Clique aqui e assine nosso plano de acesso ilimitado. Saiba mais.

por Gustavo

2 semanas atrás Gustavo

Relacionamento entre vários Models

Pessoal, tenho um Model User, um Model Profile e um Model Quiz. O User terá um profile associado, e o profile terá vários quiz associados. No model User, inseri ``` public function profile(){ return $this->belongsTo(Profile::class); } ``` No model Profile, inseri: ``` public function user(){ return $this->hasOne(User::class); } public function quizes(){ return $this->belongsToMany(Quiz::class); } ``` No model Quiz inseri: ``` public function profile(){ return $this->hasOne(Profile::class); } ``` Nas migrations, ficou em create_profiles_table: ``` public function up() { Schema::create('profiles', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->foreign('user_id')->references('id')->on('users'); $table->string('name')->nullable(); $table->string('lastname')->nullable(); $table->string('email')->nullable(); $table->timestamps(); }); } ``` Na create_quizes_table: ``` public function up() { Schema::create('quizes', function (Blueprint $table) { $table->bigIncrements('id'); $table->integer('profile_id')->unsigned(); $table->foreign('profile_id')->references('id')->on('profiles'); $table->string('quiz_name')->nullable(); $table->integer('result')->nullable(); $table->timestamps(); }); } ``` E na create_users_table: ``` public function up() { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->string('avatar')->nullable(); $table->rememberToken(); $table->timestamps(); }); } ``` Porém, dá erro abaixo: ``` SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `profiles` add constraint `profiles_user_id_foreign` foreign key (`user_id`) references `users` (`id`)) ```

13 Respostas