【问题标题】:foreign key not recognised in laravel 4.2laravel 4.2 中无法识别外键
【发布时间】:2015-08-23 19:15:54
【问题描述】:

根据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] 生产。错误:异常 'PDOException' 带有消息'SQLSTATE [42S22]:找不到列:1054 '字段列表'中的未知列'artists_id''

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

【问题讨论】:

  • 你是如何定义你们的关系的。我猜这是一对多

标签: php mysql laravel laravel-4


【解决方案1】:

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

【讨论】:

  • 当然你可以覆盖它,但是根据本书默认是artist_id,所以我们不应该覆盖它。
【解决方案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');
});

【讨论】:

  • 我明白了,你的模型很好。您是否尝试在我的答案中查看我对代码插入部分所做的更改。试试看,让我知道。
  • 我使用了您的插入代码,它可以工作。这是为什么?我在函数中使用了艺术家这个名字,因为这本书使用复数来表示专辑函数。他们说你给模型的功能起什么名字并不重要。
  • 我想这很重要,因为我认为使用该名称派生关系的键名。抛出错误是因为它正在寻找artists_id 而不是artist_id。另一件事如果你打电话给associate,你需要先保存你的对象。如果我的回答对您有帮助,您可以将其标记为已回答。很遗憾有人对我的回答投了反对票。 :(
  • @morbidCode 对于hasOne/hasMany 关系,函数的名称无关紧要。但是,对于belongsTo 关系,如果没有在第二个参数中提供外键的名称,那么它是从关系的名称派生的。您可以将函数名称更改为单数,在第二个参数中提供字段名称,甚至在第四个参数中提供关系名称(return $this-&gt;belongsTo('Artist', null, null, 'artist');
  • 糟糕!忘记了。谢谢@patricus。更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-19
相关资源
最近更新 更多