[英]Creating new polymorphic relations
在我的Laravel應用程序中,如何通過以下設置創建新的父母和子女?
class Parent extends Model
{
public function extended()
{
return $this->morphTo();
}
}
class Child extends Model
{
public function extendedFrom()
{
return $this->morphOne('App\Parent', 'extended');
}
}
class CreateParentsTable extends Migration
{
public function up()
{
Schema::create('parents', function (Blueprint $table) {
$table->increments('extended_id');
$table->string('extended_type');
});
}
}
class CreateChildrenTable extends Migration
{
public function up()
{
Schema::create('children', function (Blueprint $table) {
$table->unsignedInteger('id');
});
Schema::table('children', function (Blueprint $table) {
$table->foreign('id')
->references('extended_id')->on('parents')
->onDelete('cascade');
});
}
}
我努力了
$parent = new Parent();
$parent->save();
$child = new Child();
$parent->extended()->save($child);
但這給出了以下錯誤
Builder.php第2161行中的BadMethodCallException:
調用未定義的方法Illuminate \\ Database \\ Query \\ Builder :: save()
如果您在https://laravel.com/api/5.2/上查看API並搜索morphTo
,您會看到它返回了MorphTo
對象。 https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Relations/MorphTo.html
如果再查看此類的方法,則可以看到此類沒有save
方法。 您可能正在尋找的方法是associate
話雖如此,請嘗試以下方法。
$parent->extended()->associate($child);
您的架構也似乎已損壞。 extended_id
不能是您的主鍵(通過increments
功能自動設置)和孩子的ID。 它需要一個id
為auto_incrementing
的id
列,並從extended_id
刪除auto_incrementing
。
這樣考慮一下,這是多態的,因此多種類型的子代可能具有相同的id
。 在這種情況下,每個父母只能有一個孩子,因為extended_id
列是唯一的。
通過添加id
列,使其成為主鍵並自動遞增,並將extended_id
設置為unsigned not null
,這對我來說是有效的,並且可以適當保存。
我還將研究您的數據庫設置。 您以前應該生成的SQL錯誤,因為使用已設置的外鍵無法實現。 您可能會忽略某個地方的外鍵檢查。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.