美文网首页
laravel 分表

laravel 分表

作者: 大萝卜2022 | 来源:发表于2023-10-19 16:30 被阅读0次

    方法1: 在t_user表 的 model中 对 $this->table 重新赋值。

    namespace App\Models;
    
    class TUser extends Model
    {
    
        protected $table = ''; 
    
        public function __construct()
        {
            parent::__construct();
            $this->table = self::getTableByShopId();  //重写表名
        }
    
        public static function getTableByShopId()
        {
            $shop_id = Utils::getShopId();  //取当前店铺id
            $prefix = 't_user_';
            $num = fmod(sprintf("%u", crc32($shop_id)), 20); //取模分表,分20张;使用%u解决32位下出现负数的问题
            return $prefix . $num;
        }
    
    }
    

    调用该model的方法如下:

    TUser::query()->where('shop_id','shopHqlTPT3482')->first();  //此时查询的就是 t_user_14 这张表
    

    方法2:在t_user表 的 model中重写 getTable 方法。

    namespace App\Models;
    
    class TUser extends Model
    {
        //重写laravel 框架底层的 getTable() 方法
        public function getTable() {
            $shop_id = Utils::getShopId();  //取当前店铺id
            $prefix = 't_user_';
            $num = fmod(sprintf("%u", crc32($shop_id)), 20);//取模分表,分20张;使用%u解决32位下出现负数的问题
            return $prefix . $num;
        }
    
    }
    

    调用该model的方法如下:

    TUser::query()->where('shop_id','shopHqlTPT3482')->first();  //此时查询的就是 t_user_14 这张表
    

    方法3:在t_user表 的 model中使用 setTable 方法 将 shop_id 取模后拼接的表名,写入到model底层。

    namespace App\Models;
    
    class TUser extends Model
    {
        //获取分表后的model
        public function getSplitModel($shop_id)
        {
            return (new self())->setTable($this->getTclueTableName($shop_id))->newQuery();
        }
    
        //获取 t_user 表的表名
        public function getTuserTableName(string $shop_id)
        {
            return 't_user_' . fmod(sprintf("%u", crc32($shop_id)), 20);//取模分表,分20张;使用%u解决32位下出现负数的问题
        }
    
    }
    

    调用该model的方法如下:

    $shop_id = 'shopHqlTPT3482';
    (new TUser())->getSplitModel($shop_id)->where('shop_id','shopHqlTPT3482')->first(); 
    

    相关文章

      网友评论

          本文标题:laravel 分表

          本文链接:https://www.haomeiwen.com/subject/qauhidtx.html