php - Laravel 4.2 中无法识别外键

标签 php mysql laravel laravel-4

根据Dayle Rees

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/

相关文章:

mysql - 为什么 "where id in (n1, n2, n3, ..., n2000)"速度非常慢?

mysql - Laravel-4 本地服务器上用户的实时内容更新

javascript - 使用AJAX接收 "Uncaught SyntaxError: Unexpected token ("

php - 如何将多个变量从 ajax 传递到 php?

php - PHP 中的 MySQL : Close connection at end of script?

php - 选择多个表并按日期时间列排序显示它们

javascript - Twitter Bootstrap Dropdown PHP 链接无法打开

mysql - 使用 MySQL 5.5 在 Hibernate HQL 中从 Int 转换为 Long

php - 动态更改 div 值,laravel blade 上的导航栏

javascript - Vuejs IF 语句