gpt4 book ai didi

laravel - 自定义路由键名称不起作用

转载 作者:行者123 更新时间:2023-12-04 18:28:03 26 4
gpt4 key购买 nike

我希望模型绑定(bind)使用 id 以外的表列检索给定模型时,我会覆盖 getKeyName在模型类(Service 在这种情况下),但它不工作!

class Service extends Model{
//override
public function getRouteKey() {
return 'key';
}
}

服务表:
id  |  key(string,unique)  |  name(string)

我的路线文件:
Route::resource('services', 'ServiceController');

ServiceController :
public function show(Service $service) {
return $service;
}

但是当我去 mysiteurl.com/services/vps它显示了 404 页面。
( mysiteurl.com/services/1 有效,但我不想在 URL 中使用 id 列)

Laravel docs

最佳答案

如果您希望 Laravel 将模型绑定(bind)到具有模型 ID 以外的值的路由,您需要覆盖 getRouteKeyName()像这样的方法:

/**
* Get the route key for the model.
*
* @return string
*/
public function getRouteKeyName()
{
return 'slug';
}

关于laravel - 自定义路由键名称不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42006711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com