Laravel背包select_and_order:如何使选项列表依赖于正在编辑的模型

Laravel Backpack select_and_order: how to make options list dependent on model being edited

我有一个 select_and_order 字段可以在我的

中使用
use App\Models\Tool;
class ProjectCrudController extends CrudController
{

protected function setupCreateOperation()
{
    CRUD::addField([
        'name' => 'tools'
        'type' => 'select_and_order',
        'options' => Tool::get()->pluck('selector','id'),
    ]);

现在可能的工具取决于项目的类型,所以我不想像上面那样将所有工具返回给 options,而是想要类似

的东西
    CRUD::addField([
        'name' => 'tools'
        'type' => 'select_and_order',
        'options' => Tool
            ::projectTypeFilter($this->crud->model->type)
            ->pluck('selector','id'),
    ]);

但是新查询 returns [] 因为 - 据我所知 - $this->crud->model 没有水合。

protected function setupUpdateOperation()
{
    CRUD::addField([
        'name' => 'naam',
        'type' => 'select_and_order',
        'options' => dump($this->crud->getModel()),
    ]);
}

显示

App\Models\Project {#1779 ▼
    #guarded: array:1 [▶]
    #fakeColumns: array:1 [▶]
    #casts: array:4 [▶]
    #connection: null
    #table: null
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #withCount: []
    +preventsLazyLoading: false
    #perPage: 15
    +exists: false
    +wasRecentlyCreated: false
    #escapeWhenCastingToString: false
    #attributes: []
    #original: []
    #changes: []
    #classCastCache: []
    #attributeCastCache: []
    #dates: []
    #dateFormat: null
    #appends: []
    #dispatchesEvents: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
    #hidden: []
    #visible: []
    #fillable: []
}

如何让模型水合?

我认为您正在寻找的不是 $this->crud->getModel()(这会让您得到 Eloquent 模型 class),而是 $this->crud->getCurrentEntry() 这会让您:

  • false,如果模型还没有水合物(例如在setupCreateOperation()里面,没有当前条目可言);
  • 该 Eloquent 模型的当前条目(如果存在)(例如 setupUpdateOperation();