我正在使用 Laravel Filament (3.0) 并制作了一个法庭模型资源,效果很好。
我在配置文件表中有一个 role_id 字段,与角色表中的 id 存在关系,在配置文件表中有一个 Court_id 字段,与法庭表中的 id 存在关系。
我需要在法庭资源的法官列中显示 profile.name 属性,其中法庭 ID = 行法庭 ID 且角色 ID = 4
我可以在灯丝中添加一个 where 条件来得到这个吗?
法院资源表
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->label('Court Name')
->searchable(),
Tables\Columns\TextColumn::make('profile.fullname')
->label('Judge')
->sortable(),
])
法庭模型
public function profile()
{
return $this->belongsTo(Profile::class);
}
轮廓模型
public function court()
{
return $this->hasOne(Court::class);
}
public function role()
{
return $this->hasOne(Role::class);
}
榜样
public function profile()
{
return $this->belongsToMany(Profile::class);
}
首先,确保模型中的关系设置正确。
个人资料可能属于法庭和角色,而不是相反。
ProfileModel
public function court()
{
return $this->belongsTo(Court::class, 'court_id');
}
public function role()
{
return $this->belongsTo(Role::class, 'role_id');
}
CourtModel
public function profiles()
{
return $this->hasMany(Profile::class, 'court_id');
}
RoleModel
public function profiles()
{
return $this->hasMany(Profile::class, 'role_id');
}
现在,要显示
profile.name
(其中 role_id = 4
和 Court_id 与行的法庭 ID 匹配),您可能需要创建一个自定义列来动态计算该值。您可以在 Court 模型上使用自定义访问器,或直接在 Filament 资源中使用计算列。
Add a method to the Court model to get the judge's name:
public function getJudgeNameAttribute()
{
$judge = $this->profiles()->where('role_id', 4)->first();
return $judge ? $judge->name : 'No Judge Assigned';
}
然后,在您的 Filament 表中使用此访问器:
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->label('Court Name')
->searchable(),
Tables\Columns\TextColumn::make('judge_name')
->label('Judge')
->sortable(),
]);
Or you can also do,
直接在 Filament 资源中定义计算列,无需修改模型:
return $table
->columns([
Tables\Columns\TextColumn::make('name')
->label('Court Name')
->searchable(),
Tables\Columns\TextColumn::make('profiles')
->getStateUsing(fn ($record) => $record->profiles()->where('role_id', 4)->first()->name ?? 'No Judge Assigned')
->label('Judge')
->sortable(),
]);