【发布时间】:2015-08-23 19:15:54
【问题描述】:
所有外键列都遵循类似的命名约定。附加 _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();
});
}
这是我的雄辩模型:
<?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] 生产。错误:异常 'PDOException' 带有消息'SQLSTATE [42S22]:找不到列:1054 '字段列表'中的未知列'artists_id''
但我没有创建artists_id。这是什么意思? laravel 不应该找到artist_id,因为它应该是单数跟随by _id?
【问题讨论】:
-
你是如何定义你们的关系的。我猜这是一对多
标签: php mysql laravel laravel-4