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 關注
- 86 瀏覽
添加回答
舉報