gpt4 book ai didi

php - laravel 4.2 无法识别外键

转载 作者:行者123 更新时间:2023-11-29 02:21:40 25 4
gpt4 key购买 nike

根据 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 因为它应该是单数后跟 by _id 吗?

最佳答案

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

您应该如下定义您的关系,因为在我看来它是一对多。

在你的Artists模型中

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com