[英]Laravel get childs and all parent siblings in child-parent relation
[英]Laravel get all siblings in relation
伙計們,我需要我幫忙,我試圖通過孩子/父母表中的關系來獲取所有兄弟姐妹。 這是我的桌子
有什么方法可以獲取特定ID的所有同級對象,例如,如果ID為1,則返回ID 77和1,然后,如果44返回具有相同“ parent_id”的記錄44,56,115。
到目前為止我的代碼
public function parent() {
return $this->belongsTo(self::class , 'parent_id');
}
public function siblings()
{
????
}
/**
* Children Relation
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function children()
{
return $this->hasMany(self::class ,'parent_id')
}
所以最終我會用這個作為
self::with('parent', 'children', 'siblings')
這可以通過訪問器來完成。 在模型上定義函數:
public function getSiblingsAttribute(){
if($this->parent){
return $this->parent->children->filter(function($child){
return $child->id != $this->id;
});
}
return collect([]);
}
現在,當您嘗試訪問一個$record->siblings
,它將返回children
記錄的的parent
,與記錄過濾掉。 如果記錄沒有parent
記錄(即parent_id
為nullable()
),則它將僅返回一個空Collection
。 例如:
$records = Record::with(['parent', 'children'])->get();
foreach($records AS $record){
dd($record->siblings);
// Collection of 0 or N `Record` instances, all with the same `parent_id`
}
(不知道您的Model
被調用了什么,例如使用通用Record
,用正確的名稱替換)
旁注,由於嘗試與函數中的$this
進行比較,我不認為這可以通過關系直接完成。
編輯:要在公式中再擲一把扳手,即使parent_id
為null
,具有相同parent_id
記錄也是同級。 由於在這種情況下無法訪問$this->parent
,因此必須執行另一個查詢:
public function getSiblingsAttribute(){
if($this->parent){
return $this->parent->children->filter(function($child){
return $child->id != $this->id;
});
} else {
return $this->query()->whereNull('parent_id')->where('id', '!=', $this->id)->get();
}
return collect([]);
}
這將起作用 ,但是在循環中對記錄運行時效率極低,因為它將一次又一次地執行相同的查詢。 另外,由於無法將參數傳遞給訪問器,因此甚至不能使用原始查詢來代替filter()
。 這可能是最好的方法,而不是訪問器:
public function siblings($baseRecords){
if($this->parent){
return $this->parent->children->filter(function($child){
return $child->id != $this->id;
});
} else {
return $baseRecords->filter(function($record){
return $record->parent_id == null && $record->id != $this->id;
}
}
return collect([]);
}
通過此修改,您必須調用siblings()
作為方法:
$records = Record::with(['parent', 'children'])->get();
foreach($records AS $record){
dd($record->siblings($records));
// Collection of 0 or N `Record` instances, all with the same `parent_id`, including `null`
}
這將使用現有Collection
的Record
實例有拉出記錄parent_id
的null
,還妥善處理現有$this->parent
實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.