![](/img/trans.png)
[英]How can I get the average of a relationship and then orderBy it in Laravel 7.x?
[英]Laravel 7.x Eloquent recursive relationship - get all ids
我有一个项目, customers
通过parent_id
表自我引用。 最高的客户是应用程序,下面的客户是应用程序的直接客户,低于他们的客户是他们的客户。
我的Customer
model 关系是:
/**
* Client Parent
*
* @return \Illuminate\Database\Eloquent\Relations\belongsTo
*/
public function parent()
{
return $this->belongsTo(Customer::class, 'parent_id', 'id');
}
/**
* Client Children
*
* @return \Illuminate\Database\Eloquent\Relations\hasMany
*/
public function children()
{
return $this->hasMany(Customer::class, 'parent_id', 'id');
}
/**
* Client's All Children
*
* @return \Illuminate\Database\Eloquent\Relations\hasMany
*/
public function allChildren()
{
return $this->children()->with('children');
}
然后,在我的Controller
中,我得到了所有这样的孩子:
// Get all children customers of the user's customer
$customerTree = $customer->allChildren;
$customerIdsInTree = $customerTree->pluck('id')->toArray();
$customerIdsInTree
包含当前客户的直接后代的所有id
,但不包含他们的孩子。 如果我dd($customerTree)
,我可以将孩子视为为每个后代加载的关系。
当二级客户处于各自的直系后代客户关系中时,如何从树中提取所有id
?
或者不同的是,我如何展平集合,以便父行和子行都在同一个集合中?
您可以使用草书 function 来获取所有孩子
public function allChildren ()
{
$children_customers = new Collection();
foreach ($this->children as $child_customer) {
$children_customers->push($child_customer);
$children_customers = $children_customers->merge($child_customer->getAllChildren());
}
return $children_customers;
}
然后在您的 Controller 中,您只需提取ids
$customerIdsInTree = $customer->getAllChildren()->pluck('id');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.