在Laravel中关联同一模型的多个单个实例

我正在一个项目中,其中有一些事件,每个事件都涉及两种单独关系上的两种单一形式-预订和调查。这些表单的构造完全相同,因此似乎不必使用两个完全不同的表单模型-我想使用多态关系,但这似乎是不可能的。

构造这种关系的适当方法是什么?

  • 活动有一个或没有预订表格
  • 事件没有调查表或没有调查表
  • 表格是单独的单个表格

我尝试过的事情:

  • 多态关系:与同一模型的两个关系不兼容。
  • 具有一种关系:这使用了booking_idsurvey_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关系将每种类型的表单数量限制为一个。
cc0734 回答:在Laravel中关联同一模型的多个单个实例

我认为您的参数顺序错误。是hasOne($related,$foreignKey,$localKey)

class Event extends Model
{
    /* if you haven't changed the default primary keys,$localKey should be equal to 'id' */ 
    public function booking()
    {
        return $this->belongsTo(Form::class,'booking_form_id');
    }

    public function survey()
    {
        return $this->belongsTo(Form::class,'survey_form_id');
    }
}
class Form extends Model
{
    public function booking_event()
    {
        return $this->hasOne(Event::class,'booking_form_id');
    }

    public function survey_event()
    {
        return $this->hasOne(Event::class,'survey_form_id');
    }
}

现在有两种方法可以解决此问题。

  1. 如果表单可以同时属于这两种事件,则在访问$form->event时需要返回一个集合。
  2. 如果表单只能属于一种事件,则在访问$form->event时需要猜测哪种事件并返回模型。
# Form model
# 1. can be achieved using an accessor. Cannot be eager loaded but can be appended with the $appends Model property
public function getEventsAttribute()
{
    return collect([$this->booking_event,$this->survey_event]);
}
# Form model
# 2. can be achieved using a relationship that guesses which relation it should return. Since it returns a relationship,it can be eager loaded.
public function event()
{
    return ($this->booking_event()->count() != 0) ? $this->booking_event() : $this->survey_event();
}
本文链接:https://www.f2er.com/3158868.html

大家都在问