我正在一个项目中,其中有一些事件,每个事件都涉及两种单独关系上的两种单一形式-预订和调查。这些表单的构造完全相同,因此似乎不必使用两个完全不同的表单模型-我想使用多态关系,但这似乎是不可能的。
构造这种关系的适当方法是什么?
- 活动有一个或没有预订表格
- 事件没有调查表或没有调查表
- 表格是单独的单个表格
我尝试过的事情:
- 多态关系:与同一模型的两个关系不兼容。
- 具有一种关系:这使用了
booking_id
和survey_id
,但拒绝设置这些字段中的任何一个。 - 与类型字段有很多关系:难以保存表单,因为无法保存为单个关系。表单数量也没有限制。
class Event extends Model
{
public function booking()
{
return $this->hasOne(Form::class,'id','booking_form_id');
}
public function survey()
{
return $this->hasOne(Form::class,'survey_form_id');
}
}
...
class Form extends Model
{
public function event()
{
return $this->belongsTo(Event::class);
}
}
...
$event = new Event;
$event->name = 'Event';
$event->save();
$booking = new Form;
$booking->name = 'booking';
$event->booking()->save($booking);
$survey = new Form;
$survey->name = 'survey';
$event->survey()->save($survey);
...
Schema::create('events',function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->unsignedInteger('booking_form_id')->nullable()->index();
$table->unsignedInteger('survey_form_id')->nullable()->index();
$table->timestamps();
});
Schema::create('forms',function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
更可取的是:
- 使用多态关系,允许在应用程序的其他部分中使用表单。
- 使用多个hasOne关系将每种类型的表单数量限制为一个。