我在 PHP 8.1.0 上使用 Laravel v:9.52.16
根据Laravel Voyager自定义关系属性的文档:
假设我有一个
PlatformCategory
模型,其数据库中的相关表包含 f_name
和 l_name
列。我需要使用自定义关系属性在 PlatformCategory
的 Voyager 管理面板仪表板内显示相关模型的全名。
我尝试过以下方法:
public $additional_attributes = ['full_name'];
public function getFullNameReadAttribute()
{
return "{$this->f_name} {$this->_name}";
}
QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'full_name' in 'field list'
SELECT `full_name`, `id` FROM `platform_categories` WHERE 0 = 1 AND `platform_categories`.`deleted_at` IS NULL
The error message indicates that the database query is attempting to select a column called full_name, but it doesn't exist in the platform_categories table.
如何解决此问题并在 Voyager 管理面板中显示 PlatformCategory 模型的全名?
解决方案是编辑此文件:
tcg\voyager\resources\views\formfeilds\relationship.blade.php:
在这段代码中:
@php
$selected_keys = [];
if (!is_null($dataTypeContent->getKey())) {
$selected_keys = $dataTypeContent->belongsToMany(
$options->model,
$options->pivot_table,
$options->foreign_pivot_key ?? null,
$options->related_pivot_key ?? null,
$options->parent_key ?? null,
$options->key
)->pluck($options->table.'.'.$options->key);
}
$selected_keys = old($relationshipField, $selected_keys);
$selected_values = app($options->model)->whereIn($options->key, $selected_keys)->pluck($options->label, $options->key);
@endphp
我们需要改变
$selected_values = app($options->model)->whereIn($options->key, $selected_keys)->pluck($options->label, $options->key);
至:
$selected_values = app($options->model)->whereIn($options->key, $selected_keys)->get()->pluck($options->label, $options->key);