Laravel Filament 关系标题属性

问题描述 投票:0回答:1

显示模型的表单及其选择关系时,我想自定义它在选择中显示的标题属性。具体来说,我想让用户标题返回为“名字姓氏”。

这是标准:

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),
            ]);
    }

它返回类似这样的东西 enter image description here 但我想要名字和姓氏,而不仅仅是名字。

我确实看到了 Laravel - Filament:获取关系列的不同值 这让我觉得我可以做某种查询,比如

->relationship('user', 'first_name', function(Builder $query) {
                        $query->select('id', 'first_name', 'last_name', 'email');

但似乎没有任何效果,因为您仍然调用第二个参数中的列来查询... 我可以执行查询和 where,它将按 where 子句进行过滤...

在 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)');

这真的是唯一的方法吗?

laravel laravel-filament filamentphp
1个回答
0
投票

您可以使用

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

© www.soinside.com 2019 - 2024. All rights reserved.