简体   繁体   English

Laravel Eloquent Model 依赖注入,使用预先格式化的 Id 来查找()

[英]Laravel Eloquent Model Dependency Injection with preformated Id to find()

Normally we can simplify finding User by id logic in controller by injecting the User Class in parameter.通常我们可以通过在参数中注入User Class 来简化在 controller 中通过 id 查找用户的逻辑。 Like this:像这样:

class UserController extends Controller
{
   public function show(User $id)
   {
      return $user;
   }
}

But now I must treat the Id to find like this:但是现在我必须这样对待 Id 才能找到:

<?php
namespace App\Http\Controllers;

class UserController extends Controller
{
   public function show(User $id)
   {
      $preformattedId = '98'.$id;

      $user = User::find($preformattedId );

      return $user;
   }
}

My basic question is: how I can achieved that same trick to my preformatted id in below code like the above code?我的基本问题是:如何在下面的代码中对我的预格式化 ID 实现同样的技巧,就像上面的代码一样?

Note: I have to use the Id this way because i work with legacy database that actually adding that '98' prefix in every Id, despite that we only use characters after that prefix.注意:我必须以这种方式使用 ID,因为我使用的旧数据库实际上在每个 ID 中添加了“98”前缀,尽管我们只使用该前缀之后的字符。

You can use Inversion of Control by using explicit binding on your router.您可以通过在路由器上使用显式绑定来使用控制反转。

In your RouteServiceProvider在您的RouteServiceProvider

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    parent::boot();

    Route::bind('user', function ($value) {
        return User::find('98'.$value);
    });
}

Or in your User model或在您的User model

/**
 * Retrieve the model for a bound value.
 *
 * @param  mixed  $value
 * @param  string|null  $field
 * @return \Illuminate\Database\Eloquent\Model|null
 */
public function resolveRouteBinding($value, $field = null)
{
    return $this->find('98'.$value);
}

https://laravel.com/docs/7.x/routing#explicit-binding https://laravel.com/docs/7.x/routing#explicit-binding

You can share your route file?你可以分享你的路线文件吗?

But if your file is但是如果你的文件是

Route::get('user/{id}', 'UserController@show');

When you use当你使用

class UserController extends Controller
{
   public function show(User $id)
   {
      // you don't need use find function, it is make automatic by laravel
      $user = $id;
      return $user;
   }
}

if you want to get id, just remove User type inside show parameter如果您想获取 id,只需在show参数中删除User类型

class UserController extends Controller
{
   public function show($id)
   {
      $preformattedId = '98'.$id;

      $user = User::find($preformattedId );

      return $user;
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM