【问题标题】:Laravel replace primary key with hashids for all getLaravel 用 hashids 替换所有 get 的主键
【发布时间】:2015-07-01 12:21:33
【问题描述】:

我正在使用 laravel 4.2,我想在 url 中使用 hashids 而不是主键。它易于与单个记录一起使用。如果我使用预加载,我需要遍历所有模型并用哈希 id 替换主键。

例如。 对于每篇文章,我都需要用 hashid 更改 post_id。 对于帖子的每条评论,我都必须这样做。 对于评论的每个用户等等.. 我可以扩展模型以默认返回 hashid 吗?

【问题讨论】:

    标签: php laravel string-hashing


    【解决方案1】:

    是的,您可以使用mutators 扩展您的模型。将此方法放入您的模型中,甚至更好地放入您的所有模型都应扩展的基础模型中。

    public function getHashidAttribute()
    {
        return your_hash_function($this->attributes['id']);
    }
    

    之后,您将在模型上获得 hashid 属性,例如 $post->hashid$comment->hashid 等。

    【讨论】:

      【解决方案2】:

      您可以使用 Route::bind 方法指定应如何从 URL 段中准确解析模型,如下所示。

      Route::bind('post', function($value)
      {
          return Post::where('hashid', $value)->first();
      });
      

      如果你使用这样的路由,现在 Laravel 知道如何解析 Eloquent 模型

      /admin/{post}/edit
      

      【讨论】:

      • 这仅适用于单条记录。它不适用于急切加载。
      猜你喜欢
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 1970-01-01
      • 2016-12-18
      • 1970-01-01
      • 2016-01-01
      相关资源
      最近更新 更多