显示模型的表单及其选择关系时,我想自定义它在选择中显示的标题属性。具体来说,我想让用户标题返回为“名字姓氏”。
这是标准:
public static function form(Form $form): Form
{
return $form
->schema([
Select::make('user_id')
->relationship('user', 'first_name')
->required(),
TextInput::make('name')
->required()
->maxLength(255),
]);
}
我确实看到了 Laravel - Filament:获取关系列的不同值 这让我觉得我可以做某种查询,比如
->relationship('user', 'first_name', function(Builder $query) {
$query->select('id', 'first_name', 'last_name', 'email');
在 Laravel nova 中,你可以轻松做到这一点 https://nova.laravel.com/docs/resources/relationships.html#title-attributes-1
public static $title = 'name';
/**
* Get the value that should be displayed to represent the resource.
*
* @return string
*/
public function title()
{
return $this->first_name . ' ' . $this->last_name;
}
然而,在灯丝中,这似乎是不可能的。我确实看到了 https://filamentphp.com/docs/3.x/panels/resources/relation-managers,但这似乎只适用于关系管理器页面。
由于第二个参数应该是列名,因此建议创建一个如下所示的虚拟列:
$table->string('full_name')->virtualAs('concat(first_name, \' \', last_name)');
这真的是唯一的方法吗?
您可以使用
getOptionLabelFromRecordUsing()
方法将选项的 Eloquent 模型转换为标签
->getOptionLabelFromRecordUsing(fn (Model $record) => "{$record->first_name} {$record->last_name}")
文档:https://filamentphp.com/docs/3.x/forms/fields/select#customizing-the-relationship-option-labels