Laravel/Eloquent 通过 appointment_members table 从多态 "member_id" 获取所有约会

Laravel/Eloquent get all appointments from a polymorphic "member_id" through a appointment_members table

我有一个 appointments table 和一个 appointment_members table,我的用户需要能够通过搜索获得 appointments 的集合"member_id",可以是 PersonIncidentCustomerIDappointment_members table 有 member_idappointment_id 列,因此 member_type(也是一列)无关紧要。这都是由以前的开发人员设置的,缺少的是 Eloquent 模型上的关系。我只是创建一个简单的 GET 路由,需要 return any/all 约会 member_id。每一行都有一个约会,所以如果我要传递一个 member_id returned 10 个结果,有些人可能有 appts 而其他人没有,但在一天结束时我只需要一组与 member_id 相关的应用程序。这是 appointment_members table 的屏幕截图:

如果我在 appointment_members 上创建一个简单的 hasOne 约会关系:

public function appointments()
{
    return $this->HasOne(Appointment::class, 'id', 'appointment_id');
}

我可以得到 appointment_members 的集合及其各自的 appointment,但不确定如何将其归结为只得到 appointments。我的一种解决方法是使用 HasOne,然后 pluck/filter 约会:

$appointmentMembers = AppointmentMembers::where('member_id', $request->input('memberId'))->get();
$appointments = $appointmentMembers->pluck('appointments')->filter();

想知道是否有人可以找到更好的方法来解决这个问题。谢谢!

我可能不明白,但如果成员类型不重要,我可能会在这里采用最简单的方法。

table 已经设置为处理 belongsToMany 或 morphMany,因此在成员 class 上创建关系(或者如果您没有父成员 class, 将它贴在每个类型的人、事件等上。当然,你也可以通过 poly 来完成,但这是一个简单的例子来获得你需要的东西):

public function appointments()
{
    return $this->belongsToMany(Appointment::class)->withPivot('member_type');
} 

然后只需查询您需要预约的成员对象(使用 poly 就可以完成这一步):

$allAppointmentsForID = $member->appointments();
$appointments = $allAppointmentsForID->wherePivot('member_type', $whateverClassThisIS);

以上考虑了 member_type。如果这无关紧要,您可以只使用顶行。

您的原始数据库设置为处理多态关系,因此如果您想要的不仅仅是约会,您也可以这样设置。现在,您需要将 TYPE 添加到查询中以涵盖不同的 classes.

如果成员类型很重要,成员上的多态性可能是这样的class:

public function appointments()
{
    return $this->morphMany(Appointment::class, 'memberableOrmember_typeOrWhatever');
}

然后就可以一行查询成员对象了

$appointments = $member->appointments();