2017-02-25 53 views
0

我正在製作一個具有遞歸結構的模型,如下所示。 Concept模型可以具有父級和子級概念,並且該模型按預期工作。我的問題是實現一個頁面來添加兩個概念之間的鏈接。如何鏈接Laravel 5中的遞歸數據結構?

<?php 

namespace App\Models; 

use Illuminate\Database\Eloquent\Model; 

class Concept extends Model 
{ 
    // 
    public function parentConcepts() 
    { 
     return $this->belongsToMany('App\Models\Concept','concept_concept','parent_concept_id','child_concept_id'); 
    } 
    public function childConcepts() 
    { 
     return $this->belongsToMany('App\Models\Concept','concept_concept','child_concept_id','parent_concept_id'); 
    } 
    public function processes() 
    { 
     return $this->hasMany('App\Models\Process'); 
    } 
} 

我該怎麼做呢?我會利用模型中的pivot屬性,還是爲concept_concept表創建一個新模型和控制器?任何幫助將非常感激!

回答

0

在利用attach()函數的控制器中創建新函數是解決方案的關鍵。

public function storeChildLink(Request $request) 
{ 
    //get the parent concept id 
    $concept = Concept::find($request->input('parentConceptId')); 
    //attach the child concept 
    $concept->childConcepts()->attach($request->input('childConceptId')); 

    $concept->save(); 

    return redirect()->route('concept.show', ['id' => $request['parentConceptId']])->with('status', 'Child Concept Successfully Linked'); 
} 

public function storeParentLink(Request $request) 
{ 
    //get the child concept id 
    $concept = Concept::find($request->input('childConceptId')); 
    //attach the parent concept 
    $concept->parentConcepts()->attach($request->input('parentConceptId')); 

    $concept->save(); 

    return redirect()->route('concept.show', ['id' => $request['childConceptId']])->with('status', 'Parent Concept Successfully Linked'); 
}