Laravel MorphToMany 不适用于多列



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对象时,emailsforms的对象为空。

有人能帮我吗?

根据您的问题和评论:

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

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

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');
}
}

相关内容

  • 没有找到相关文章

最新更新