在我的应用程序中,我有一个名为“Order”的模型,它遵循默认的 Laravel 行为,并带有一个名为“hash”的附加唯一字符串属性:
class Order extends Model {
// $table = 'orders';
// $primaryKey = 'id';
// $incrementing = true;
$hash = 'a1b2c3d4e5f6g7h8i9';
// many related models
}
函数 Model::find 的默认行为是查找主键,这是我绝对想要保留的功能。目前我的 routes/api.php 包含这样的功能:
public function show(Request $request, Order $order) {
// the order will be loaded via the id
// if the model is not found an exception is thrown
}
在某些情况下,我现在想注入相同的订单,但通过订单的哈希进行搜索,所以我假设我的 api.php 看起来像这样:
public function show(Request $request, OrderSearchByHash $order) {
// the order will be loaded via the id
// if the model is not found an exception is thrown
}
问题来了:这是否可以实现,如果是,如何实现?我实际上并不需要源代码,而是对我必须去的方向的提示。我已经阅读了有关 ServiceProviders 和 Facades 的内容,尝试创建一个扩展模型(但我必须“修补”所有关系,因为数据透视表会有不同的名称)以及 Laravel 文档中的许多其他内容,但我仍然没有甚至确切地知道是否以及什么涵盖了我的特定问题?
有人给我提示吗?提前致谢!
您可以使用自定义模型绑定:
控制器中的两个方法都将如下所示:
public function show(Request $request, Order $order) {
}
Route::get('orders/{order}', 'OrderController@show');
Route::get('orders-by-hash/{order_by_hash}', 'OrderController@show');
Route::bind('order_by_hash', function ($value) {
// Use your logic for finding your order by hash
return Order::where[...]->first();
});
您还可以仅在连接时授权通过 ID 查找订单:
Route::bind('order', function ($value) {
// Use your logic for finding your order by hash
return Order::where[...]->when(auth()->check(), function()
$query->orWhere(function($query){
$query->where(order_id, $value)
->where(user_id, auth()->id());
})
)->first();
});
So when you are connected, IF an order with the id belongs to the user , you can find it that way
This is only relevant if your route using an id and your hash are using the same controller's methods, else I recommend to use 2 different model bindings
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句