1 回答
TA贡献1852条经验 获得超1个赞
根据您的意见进行更新
似乎您在国家/地区和乡村价格之间有一对一的关系。它可以理解如下:“一个国家有一个国家价格,每个国家价格属于一个且只有一个国家”。
该关系可以通过以下方式建立:国家模型
public function countryPrice()
{
return $this->hasOne(CountryPrice::class);
}
国家价格模型
public function country()
{
return $this->belongsTo(Country::class);
}
然后相应地更新 nova 实体:国家/地区资源
public function fields(Request $request)
{
return [
// ...
HasOne::make('Country Prices'),
// ...
];
}
国家价格资源
public function fields(Request $request)
{
return [
// ...
BelongsTo::make('Country'),
// ...
];
}
然后在国家/地区 nova 资源中指定标题属性,如我在旧答案中在下面解释的那样:
/**
* The single value that should be used to represent the resource when being displayed.
*
* @var string
*/
public static $title = 'name';
生成的系统将允许您在从 nova 界面创建国家/地区价格记录时从选择框中选择单个国家/地区。在国家/地区 nova 指数中,您还将看到每个国家/地区及其指定的价格。
我希望这是你需要的正确行为。如果不正确,请告诉我,我会在Stack Overflow上打开一个聊天,以便我们可以准确地整理出您需要的内容并解决问题。
下面的旧答案
修复关系
我认为你们的关系设置错了。从您发布的表架构来看,看起来每个架构都可以有很多,因为您将列放在 .CountryCountryPricecountry_idcountry_prices
因此,如果“国家/地区具有多个国家/地区价格”,则“每个国家/地区价格属于一个国家/地区”。
如果我误解了你们的关系,请在评论中告诉我正确的关系,我会修复我的答案。
您可以按如下方式设置这两个关系:
国家模式
public function countryPrices()
{
return $this->hasMany(CountryPrice::class);
}
国家价格模型
public function country()
{
return $this->belongsTo(Country::class);
}
然后更新两个 Nova 资源以匹配新的关系:
国家资源
public function fields(Request $request)
{
return [
// ...
HasMany::make('Country Prices'),
// ...
];
}
国家价格资源
public function fields(Request $request)
{
return [
// ...
BelongsTo::make('Country'),
// ...
];
}
解释当前异常
应用\国家/地区价格::获取国家/地区名称必须返回关系实例
您收到的错误与Nova本身无关。发生这种情况是因为模型中定义的每个(非静态)方法都应该是查询范围、模型访问器/赋值器或关系。
这意味着,如果定义 ,它将被视为关系,并且需要返回关系实例,但您将返回一个字符串。getCountryName
在您的用例中,您实际上并不需要定义访问器。您可以使用:
$countryPrice->country->name
在实例上。CountryPrice
修复显示标题
要修复资源上的选择输入中显示的选项,您必须定义一个属性或方法,该属性或方法将在您链接到的 Nova Resource 类中完全用于该目的(在您的示例中)。CountryBelongsToCountryPricetitleCountry
您可以使用:
/**
* The single value that should be used to represent the resource when being displayed.
*
* @var string
*/
public static $title = 'name';
或者,如果您需要从其他特性/转换中计算标题属性:
/**
* Get the value that should be displayed to represent the resource.
*
* @return string
*/
public function title()
{
// You can make advanced transformations/processing of any value here
// $this will refer to the current resource instance.
return $this->name;
}
这也适用于全球检索。
- 1 回答
- 0 关注
- 102 浏览
添加回答
举报
