繁体   English   中英

创建新的多态关系

[英]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。 它需要一个idauto_incrementingid列,并从extended_id删除auto_incrementing

这样考虑一下,这是多态的,因此多种类型的子代可能具有相同的id 在这种情况下,每个父母只能有一个孩子,因为extended_id列是唯一的。

通过添加id列,使其成为主键并自动递增,并将extended_id设置为unsigned not null ,这对我来说是有效的,并且可以适当保存。

我还将研究您的数据库设置。 您以前应该生成的SQL错误,因为使用已设置的外键无法实现。 您可能会忽略某个地方的外键检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM