正在创建新的多态关系


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()

如果您在此处查看APIhttps://laravel.com/api/5.2/搜索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,并从extended_id中删除auto_incrementing

这样想吧,这是多态的,所以多种类型的子项可能具有相同的ids。在这种情况下,每个父项可能只有一个子项,因为extended_id列是唯一的。

通过添加id列,使其成为主键,并自动递增并将extended_id设置为仅unsigned not null,这对我来说很有效,而且保存得很好。

我还想看看你的数据库设置。您以前所做的应该是生成SQL错误,因为使用您设置的外键不应该发生这种错误。您可能在某个地方忽略了外键检查。