All foreign key columns follow a similar naming convention. The singular form of the related model appended with _id.
考虑此迁移:
class CreateTables extends Migration {
// ...
public function up()
{
Schema::create('artists', function($table) {
$table->increments('id');
$table->string('name',64);
$table->timestamps();
});
Schema::create('albums', function($table) {
$table->increments('id');
$table->string('name',64);
$table->integer('artist_id')->unsigned();
$table->foreign('artist_id')->references('id')->on('artists');
$table->timestamps();
});
}
这是我的 Eloquent 模型:
<?php
// Artist model
class Artist extends Eloquent {
public function albums() {
return $this->hasMany('Album');
}
}
<?php
// Album model
class Album extends Eloquent {
public function artists() {
return $this->belongsTo('Artist');
}
}
我这样使用它们:
Route::get('/', function() {
$artist = new Artist;
$artist->name = "Morbid Angel";
$artist->save();
$album = new Album;
$album->name = "Altars of Madness";
$album->artists()->associate($artist);
$album->save();
return View::make('hello');
});
根据日志,这似乎不起作用:
[2015-06-09 06:01:12] production.ERROR: exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'artists_id' in 'field list''
但我没有创建artists_id
。这是什么意思? laravel 不应该找到 artist_id
因为它应该是单数,后面跟着 _id
吗?
最佳答案
这是你的问题。您已将您的关系命名为 artists
,但它应该是 artist
。这就是为什么它要查找名为 artists_id
的列。
您应该如下定义您的关系,因为在我看来它是一对多。
在您的艺术家
模型中
public function albums()
{
return $this->hasMany('Album');
}
在您的相册
模型中
public function artist()
{
return $this->belongsTo('Artist');
}
然后尝试您的代码。
Route::get('/', function() {
$artist = new Artist;
$artist->name = "Morbid Angel";
$artist->save();
$album = new Album;
$album->name = "Altars of Madness";
$artist->albums()->save($album);
return View::make('hello');
});
关于php - Laravel 4.2 中无法识别外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30724107/