我正在制作一个具有递归结构的模型,如下所示。概念模型可以具有父母和子女概念,并且该模型按预期工作。我的问题是实施一个页面以添加两个概念之间的链接。
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
class Concept extends Model
{
//
public function parentConcepts()
{
return $this->belongsToMany('AppModelsConcept','concept_concept','parent_concept_id','child_concept_id');
}
public function childConcepts()
{
return $this->belongsToMany('AppModelsConcept','concept_concept','child_concept_id','parent_concept_id');
}
public function processes()
{
return $this->hasMany('AppModelsProcess');
}
}
我该怎么做?我会在模型中利用枢轴属性,还是会为concept_concept表创建新的模型和控制器?任何帮助将不胜感激!
在控制器中创建一个新功能,该功能使用the 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');
}