3

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有空对象时。

谁能帮我?

4

1 回答 1

1

从您的问题和评论中:

有表格、电子邮件和服务。表单可以与任意数量的不同类型的模型相关联。电子邮件可以与任意数量的不同类型的模型相关联。一个服务可以有很多表单,一个服务可以有很多电子邮件。

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

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');
    }
}
于 2020-07-09T15:54:16.837 回答