如何 link Laravel 5 中的递归数据结构?
How to link a recursive data scructure in Laravel 5?
我正在制作一个具有递归结构的模型,如下所示。 Concept 模型可以有父概念和子概念,并且模型按预期工作。我的问题是实现一个用于在两个概念之间添加链接的页面。
<?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 table 创建一个新的模型和控制器?任何帮助将不胜感激!
在使用 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');
}
我正在制作一个具有递归结构的模型,如下所示。 Concept 模型可以有父概念和子概念,并且模型按预期工作。我的问题是实现一个用于在两个概念之间添加链接的页面。
<?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 table 创建一个新的模型和控制器?任何帮助将不胜感激!
在使用 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');
}