簡體   English   中英

Laravel得到所有同胞的關系

[英]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_idnullable() ),則它將僅返回一個空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_idnull ,具有相同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`
}

這將使用現有CollectionRecord實例有拉出記錄parent_idnull ,還妥善處理現有$this->parent實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM