如何在 Create Crud select 仅启用的字段中显示

How to show in a Ceate Crud select only enabled fileds

我开始研究 Laravel 和 Laravel 的背包。

在当前项目中我有两个 tables:

Group:
id
name
enabled

Manager:
id
name
group_id

在“创建新管理器”页面中,表单显示 select,其中包含 table 中的所有组。有一种方法可以只显示 enabled=1 ?

的组

我尝试在 Backpack 文档中进行搜索,但没有找到任何内容。

编辑

这是ManagerCrudController中的代码

class ManagerCrudController extends CrudController
{
 public function setup()
    {
        CRUD::setModel(\App\Models\Manager::class);
        CRUD::setRoute(config('backpack.base.route_prefix') . '/manager');
        CRUD::setEntityNameStrings('manager', 'managers');
    }
protected function setupCreateOperation()
    {
        CRUD::setValidation(ManagerRequest::class);

        CRUD::field('group_id');
        CRUD::field('name');
    }
}

这是组模型和经理模型

class Group extends Model
{
    use \Backpack\CRUD\app\Models\Traits\CrudTrait;
    use HasFactory, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'enabled',
    ];

    protected $casts = [
        'id' => 'integer',
        'enabled' => 'integer',
    ];


    public function managers()
    {
        return $this->hasMany(\App\Models\Manager::class);
    }
}

class Manager extends Model
{
    use \Backpack\CRUD\app\Models\Traits\CrudTrait;
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'group_id',
        'name',
    ];

    protected $casts = [
        'id' => 'integer',
        'group_id' => 'integer',
    ];

    public function group()
    {
        return $this->belongsTo(\App\Models\Group::class);
    }
}

好的,我终于发现我必须以这种方式更改 ManagerCrudController 中的字段,现在它起作用了:

From this:
CRUD::field('group_id');

To this:
$this->crud->addField([  // Select
            'label'     => "Gruppo",
            'type'      => 'select',
            'name'      => 'group_id', // the db column for the foreign key

            // optional
            // 'entity' should point to the method that defines the relationship in your Model
            // defining entity will make Backpack guess 'model' and 'attribute'
            'entity'    => 'group',

            // optional - manually specify the related model and attribute
            'model'     => "App\Models\Group", // related model
            'attribute' => 'name', // foreign key attribute that is shown to user

            // optional - force the related options to be a custom query, instead of all();
            'options'   => (function ($query) {
                 return $query->orderBy('name', 'ASC')->where('enabled', 1)->get();
             }), //  you can use this to filter the results show in the select
         ]);

谢谢大家