Laravel MorphToMany不适用于多列

lovecoding-laravel:

Laravel版本:7.0这是我的桌子。

    Schema::create('model_email_form', function (Blueprint $table) {
        $table->id();
        $table->string('model_type');
        $table->unsignedBigInteger('model_id');
        $table->unsignedBigInteger('email_id');
        $table->unsignedBigInteger('form_id');
        $table->timestamps();
    });

这是我的Service模特。

    public function forms()
    {
        return $this->morphToMany(
            Form::class,
            'model',
            'model_email_form',
            'model_id',
            'form_id'
        );
    }
    public function emails()
    {
        return $this->morphToMany(
            Email::class,
            'model',
            'model_email_form',
            'model_id',
            'email_id'
        );
    }

我插在数据model_email_form表中,但是,当我得到service model的对象,emails并且forms有空对象。

谁能帮我?

Kurt Friars:

根据您的问题和评论:

有表格,电子邮件和服务。表单可以与任何数量的不同类型的模型相关联。电子邮件可以与许多不同类型的模型相关联。服务可以具有许多表格,服务可以具有许多电子邮件。

以此为基础,这就是我们的模式:

Schema::create('forms', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name'); // as an example
    ...
    $table->timestamps();
});

Schema::create('formables', function (Blueprint $table) {
    $table->unsignedBigInteger('form_id'); // the id of the form
    $table->unsignedBigInteger('formable_id'); // the associated model's id
    $table->string('formable_type'); // The associated model's class name
});

Schema::create('emails', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('subject'); // as an example
    ...
    $table->timestamps();
});

Schema::create('emailables', function (Blueprint $table) {
    $table->unsignedBigInteger('email_id'); // the id of the email
    $table->unsignedBigInteger('emailable_id'); // the associated model's id
    $table->string('emailable_type'); // The associated model's class name
});

Schema::create('services', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name'); // as an example
    ...
    $table->timestamps();
});

使用该架构,我们可以创建具有以下关系的以下模型:

class Form extends Model
{
    public function services()
    {
        return $this->morphedByMany(Service::class, 'formable');
    }
   
    // Add the other morphedByMany relationships of forms
}

class Email extends Model
{
    public function services()
    {
        return $this->morphedByMany(Service::class, 'emailable');
    }
   
    // Add the other morphedByMany relationships of emails
}

class Service extends Model
{
    public function forms()
    {
        return $this->morphedToMany(Form::class, 'formable');
    }
   
    public function emails()
    {
        return $this->morphedToMany(Email::class, 'emailable');
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章