2017-09-19 9 views
1

私はこのような構造でデータベーステーブル "文書" を持っている:私のLaravelモデルDocument.phpブレッドクラムアレイフォームをLaravelで取得するにはどうすればよいですか?

// table documents: 
|id|parent_id|name  | 
|1 |0  |foldername1| 
|2 |0  |foldername2| 
|2 |1  |subfolder | 

を、私はこの方法があります:

public function parent() 
{ 
    return $this->belongsTo($this, 'parent_id', 'id'); 
} 

しかし、どのように、私は得ることができますが私のパンくずリストは私のコントローラにありますか?

私は多くのことを試してみたが、それは働いていない... :(

DocumentController.php:?

// NOT WORKING EXAMPLE!! 
public function index() 
{ 
    $file = Document::findOrFail(2); 

    if ($file->parent) { 
     $breadcrumbs[] = $this->setBreadcrumbs($file->parent); 
    } 
    dd($breadcrumbs); 

} 

private function setBreadcrumbs(Document $file) 
{ 
    $arr = []; 
    if ($file->parent) { 
     $arr[] = $this->setBreadcrumbs($file->parent); 
    } else { 
     return $arr; 
    } 
    return $file->id; 
} 
+0

なぜ 'setBreadCrumbs()'は再帰的に呼び出されますか?あなたは$ file-> parentを調べて、最初の場所に結果があるかどうかを確認することができます。 –

+0

はい、$ file-> parentは正しい親の値を返します。しかし、私のコントローラで$ file-> parentを再帰的に実行するにはどうすればいいですか? – angelique000

答えて

1

方法だけでパンくずリストがモデルに属性を持っていることについて

class File { 

    public function getBreadcrumbsAttribute() 
    { 
     if($this->parent){ 
      return array_merge($this->parent->breadcrumbs, [$this->id]); 
     } 
     return [$this->id]; 
    } 
} 

次に、$file->breadcrumbsと呼ぶことができます。これは、ファイル名やリンクを配列に渡す必要がある場合には、簡単に適応できます代わりに。

+0

ありがとう!これは私が必要としているexaclyです! – angelique000

+0

少し質問...どのように私の配列のキーとしてIDを得ることができますか? 私は試しました: return array_merge($ this-> parent-> breadcrumbs、[$ this-> id => $ this-> original_name])と: 返す[$ this-> id => $ this-> original_name ]; でも私のキーは0,1,2などです。 – angelique000

+0

数字キーを使用すると、ブレッドクラムを正しく表示するために必要な順序が失われる可能性があります。必要ならば、 '[$ this-> id]'を '['id' => $ this-> id、 'name' => $ this-> original_name]'に置き換えて、利用可能なIDと名前の両方。 – Jeff

関連する問題