如何利用拉拉威尔中的自我参照关系将父母与子女(整个家庭)归为一体



我在Laravel中有一个客户模型。字段示例:

  • id:integer
  • 第一个:字符串
  • last:字符串
  • parent_id:整数

我可以使用以下方法获取家长和孩子:

public function parent()
{
return $this->belongsTo(Customer::class);
}
public function members()
{
return $this->hasMany(Customer::class, 'parent_id','id');
}

有没有一种方法可以添加一个同时返回父对象(如果有(和成员(如果有的话(的族方法?我试过了:

public function family()
{
return $this->with('members');
}

但是它没有返回关系实例,所以它不起作用。有什么想法吗?我可以在控制器中通过以下操作来解决它:$family = !$customer->parent_id ? $customer->members->push($customer) : $customer->parent->members->push($customer->parent);

感谢Tim Lewis的评论,在其他人搜索解决方案的情况下,以下是行之有效的方法。首先,parent_id字段将指示他们是否是户主。如果为null,则它们是父级。我修改了我的模型类,添加了以下内容:

public function getFamilyAttribute()
{
return !$this->parent_id ? $this->members->prepend($this) : $this->parent->members->prepend($this->parent);
}

现在,我可以直接打电话给客户,而不是到处都是逻辑;家庭和所有成员都以父成员作为第一个成员显示。

为什么这很重要?因为在我的申请中,我需要知道在上一个计费期内有多少客户访问过。我还需要知道整个家庭的工资是多少(有时其他成员会在一个月内支付账单(。我现在可以使用其他方法并简单地调用它们。

示例:

public function getFamilyApptsAttribute() {
return Appt::select(['id','customer_id','appt_date','appt_time','appt_note')->with('patient')->whereIn('customer_id',$this->family->pluck('id')->toArray())->orderByDesc('id')->get();
}

最新更新