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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测