BackPack是一款Laravel开发框架的扩展包,用于简化操作和管理后台。在使用BackPack进行数据管理时,常常需要从数据库中取出某个对象的标题,并且在后台显示,但是在保存数据时需要利用该对象的ID。因此,需要实现以下功能:从数据库中选择标题,并将其与对应的ID一起保存。
以下是代码示例:
1.在模型中定义getTitle方法获取标题。
public function getTitle()
{
return $this->title; //返回标题
}
2.在CrudController中使用select2方法,实现标题选择框。
$this->crud->addField([
'label' => 'Object',
'type' => 'select2',
'name' => 'object_id', //保存的是ID而不是标题
'entity' => 'object', //对应的实体
'attribute' => 'title', //显示的属性
'model' => 'App\Models\Object', //对应的模型
]);
3.在保存数据时,需要根据标题获取对应的ID并存入数据库。
$this->crud->onUpdate(function (Request $request) {
$title = $request->input('object_id');
$object = Object::where('title', $title)->first();
$request->merge(['object_id' => $object->id]);
return $this->crud->update($request);
});
$this->crud->onCreate(function (Request $request) {
$title = $request->input('object_id');
$object = Object::where('title', $title)->first();
$request->merge(['object_id' => $object->id]);
return $this->crud->create($request);
});
通过以上方法,我们实现了从数据库中选择标题,但是保存ID的功能,这也是BackPack中经常使用的操作。