2017-02-25 4 views
0

私は以下のように再帰的な構造を持つモデルを作っています。概念モデルは親概念と子概念を持つことができ、モデルは期待どおりに機能します。私の問題は、2つの概念間のリンクを追加するためのページを実装することです。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'); 
    } 
} 

どうすればいいでしょうか?モデルのピボット属性を使用するか、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'); 
} 
関連する問題