1 回答

TA貢獻1784條經驗 獲得超7個贊
是否有理由不能將單個唯一值(例如自動增量 ID)作為主鍵,然后將兩個附加索引作為唯一復合索引?
這將解決您的路由參數(shù)問題,因為您只有一個主鍵:
/api/peopleDatas/{id}
您的遷移將包括唯一復合索引的規(guī)范:
$table->unique(['personel_id', 'valid_for_quarter']);
這樣,您的組合列保持唯一性,而您的路線被簡化為單個 ID,并且您的關系也可以使用單個 ID。這將提高性能并簡化代碼。
或者,如果您絕對必須有一個復合主鍵,您可以這樣做。您的遷移需要:
$table->primary(['personel_id', 'valid_for_quarter']);
您的模型需要為保存查詢設置鍵(請參閱鏈接) https://blog.maqe.com/solved-eloquent-doesnt-support-composite-primary-keys-62b740120f
protected function setKeysForSaveQuery(Builder $query)
{
$query
->where('personel_id', '=', $this->getAttribute('personel_id'))
->where('valid_for_quarter', '=', $this->getAttribute('valid_for_quarter'));
return $query;
}
路由綁定的最佳解決方案是使用顯式路由模型綁定(請參閱文檔鏈接),您的參數(shù)是兩個鍵的分隔組合:
/api/peopleDatas/{people_data}人員數(shù)據(jù) =1_3例如
https://laravel.com/docs/5.8/routing#explicit-binding
在您的路線服務提供商中,您需要指定解析邏輯,如下所示:
public function boot()
{
parent::boot();
Route::bind('people_data', function ($value) {
return App\PeopleData::where('personal_id', explode('_', $value)[0])
->where('valid_for_quarter', explode('_', $value)[1])
->first() ?? abort(404);
});
}
- 1 回答
- 0 關注
- 175 瀏覽
添加回答
舉報