dsnrixf6765 2014-08-01 14:28
浏览 121
已采纳

laravel雄辩的特殊UUID主键

I have a users table that doesn't use an auto increment primary key, instead it uses a binary uuid primary key. I set up my custom model to interact with my table however, I'm having trouble trying to find records by using ::find() because for a case like this, this uuid needs to searched by using HEX() and UNHEX() mysql functions. How to I override this and have whatever is in ::find() to be hexed. The name of the model is Player.

So if I was to try to find a user with a uuid of 9d823b9eec224cbea10b69bec2c5adef, I cannot find them by doing:

Player::find('9d823b9eec224cbea10b69bec2c5adef') since the uuid needs to be unhexed.

I've tried Player::find("UNHEX('9d823b9eec224cbea10b69bec2c5adef')"); with no results.

Here's my model so far:

class Player extends Eloquent {

    protected $table = 'players';
    protected $connection = 'game';
    protected $primaryKey = 'uuid';

    public $incrementing = false;    
    public $timestamps = false;


}

The datatype for uuid is binary(16)


Update

I've got it to work by using Player::find(DB::raw("UNHEX('9d823b9eec224cbea10b69bec2c5adef')")); however this is a lot to write every time I need to look up a user.

Is there any way I can have the parameter for ::find() always run through DB::raw("UNHEX('uuid')") or be passed through the function hex2bin()?

I am 100% certain I will always be using UUID so I want to override ::find(), not create a new method.

  • 写回答

3条回答 默认 最新

  • doujianglin6704 2014-08-01 14:52
    关注

    I would try to unhex it in PHP prior to passing it to mysql:

    Player::find(hex2bin('9d823b9eec224cbea10b69bec2c5adef'));
    

    You could add this method to your Player class:

    public static function findUUID($uuid) {
    
        return self::find(hex2bin($uuid));
    
    }
    

    Now any where in your project you can call it like:

    $result = Player::findUUID('9d823b9eec224cbea10b69bec2c5adef');
    

    If you do not want to declare it statically you can:

    public function findUUID($uuid) {
    
        return self::find(hex2bin($uuid));
    
    }
    

    and then reference it in your code with:

    $result = new Player;
    $result->findUUID('9d823b9eec224cbea10b69bec2c5adef');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 【急】在线问答CNC雕刻机的电子电路与编程
  • ¥60 在mc68335芯片上移植ucos ii 的成功工程文件
  • ¥15 笔记本外接显示器正常,但是笔记本屏幕黑屏
  • ¥15 Python pandas
  • ¥15 蓝牙硬件,可以用哪几种方法控制手机点击和滑动
  • ¥15 生物医学数据分析。基础课程就v经常唱课程舅成牛逼
  • ¥15 云环境云开发云函数对接微信商户中的分账功能
  • ¥15 空间转录组CRAD遇到问题
  • ¥20 materialstudio计算氢键脚本问题
  • ¥15 有没有代做有偿主要做数据可视化部分即可(2023全国高考更省一本线理科类)