laravel 4.2

时间:2015-06-09 06:04:27

标签: php mysql laravel laravel-4

根据Dayle Rees

所有外键列都遵循类似的命名约定。附加_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] production.ERROR:异常'PDOException',消息'SQLSTATE [42S22]:未找到列:1054'字段列表'中的未知列'artists_id'

但我没有创建artists_id。这是什么意思?不应该laravel找到artist_id,因为它应该是单数跟by _id

2 个答案:

答案 0 :(得分:2)

这是你的问题。您已将自己的关系命名为artists,但它应为artist 。这就是它寻找名为artists_id的列的原因。

你应该按照以下方式定义你的关系,因为在我看来它是一对一的。

Artists模型中

public function albums()
{
    return $this->hasMany('Album');
}

Albums模型中

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');
});

答案 1 :(得分:0)

在您的艺术家模型中尝试return $this->hasMany('Album', 'artist_id');

相关问题