4
I’m having trouble creating the foreign key in Migration.
I am working with PHP, LARAVEL 5.3 and MYSQL. You’re making the following mistake:
Below is my code:
Table Migration categs
class CreateCategsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categs', function (Blueprint $table) {
$table->increments('id');
$table->text('nome_cat');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categs');
}
}
Migration from the Products Table
class CreateProdutosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('produtos', function (Blueprint $table) {
$table->increments('id');
$table->text('nome');
$table->text('descricao');
$table->integer('categs_id');
$table->foreign('categs_id')->references('id')->on('categs');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('produtos');
}
}
Model categs
use Illuminate\Database\Eloquent\Model;
class categ extends Model
{
//Relacionamento 1:n Categoria dos produtos
public function produtos()
{
return $this->hasMany('App\produtos');
}
}
Model products
use Illuminate\Database\Eloquent\Model;
class Produtos extends Model
{
//
public function categoria()
{
return $this->belongsTo('App\categ');
}
}
Take the simple quotes from FK’s name
– Don't Panic
I took it off, and it didn’t work.
– Daniel dos Santos
do it this way and check if it worked.
$table->integer('categs_id')->unsigned()
– DNick
Tip: It’s a bad idea to put Foreign Keys together with field creation. By default, always use a Migration for creating fields and another for creating Foreign Keys.
– Wallace Maxters