mysql - 在 Laravel 中存储 32 位二进制文​​件的正确方法

标签 mysql laravel binary bit laravel-migrations

目前我正在使用

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('test_binary', function (Blueprint $table) {
        $table->increments('id');
        $table->char('binary_number', 32)->charset('binary'); // From: https://stackoverflow.com/a/62615777/5675325
        $table->timestamps();

    });
}

存储 32 位二进制数,例如 00000000000000000000000000000010,即 result of

$binaryString = str_pad(base_convert(2, 10, 2),32,'0',STR_PAD_LEFT);

并存储在这样的表中

enter image description here

播种机有类似的东西

'binary_number' => str_pad(base_convert(2, 10, 2),32,'0',STR_PAD_LEFT),

关于数据库中的 BINARY 类型(如上图所示),apokryfos建议

I think bit is what you need here, though I'm not fully sure that Laravel supports that so you might need to use DB::raw("b'000000010'") to insert data to bit columns

Jarek Tkaczyk同意(我不完全确定 Laravel 支持那个)部分

Having bit type field means that you need to use raw values as a workaround whenever you are inserting/updating that field. (...)

DB::table('table')->insert(['bit_field' => DB::raw(0)]); // inserts 0

他建议 OP 在可能的情况下更改为 tinyint(对于可以具有值 0 或 1 的列的情况)。

这可能暗示如果想通过 Laravel 迁移处理大小为 32 的位,则需要使用比 tinyint 更大的整数。

所以,如果我想要一个大小为 32 的整数,Alexey Mezenin指出

You can't do this, but you can use different types of integer:

$table->bigInteger()
$table->mediumInteger()
$table->integer()
$table->smallInteger()
$table->tinyInteger()

应该发生什么

$table->char('binary_number', 32)->charset('binary');

然后如何容纳32位二进制数作为值以及如何插入/检索这样的记录?

最佳答案

数据库中的输入应为无符号整数类型,即 32 位大小或 4 个字节。

$table->unsignedInteger();

因此,保存值应该不是问题,您只需使用 bindec() 将二进制值转换为十进制值,或者使用常量方法进行简单的 SUM。

对于查询部分,假设您想要第 3 位为 1 的结果。

$query->whereRaw('BIT_COUNT(4 & fieldName) = 1')

我习惯于为相关模型上的那些值分配常量,这有助于维护代码和调试。

class User extends Model {
const NOTIFICATION_FRIEND = 1; //2^0 or 0000 ... 0000 0001
const NOTIFICATION_CLIENT = 2; //2^1 or 0000 ... 0000 0010
const NOTIFICATION_APP = 4; //2^2 or 0000 ... 0000 0100
const NOTIFICATION_VENDOR = 8; //2^3 or 0000 ... 0000 1000
//...
// up to a max of 32nd one wich is 2147483648 (or 2^31)
}

所以查询看起来像这样

$usersToBeNotified = $currentUser->friends()
    ->whereRaw('BIT_COUNT('.User::NOTIFICATION_FRIEND .' & notification_preferences) = 1')
    ->get();

要构建要从表单中存储的整数,只需对常量求和即可。

$user->notification_preferences  = User::NOTIFICATION_FRIEND + User::NOTIFICATION_APP;

关于mysql - 在 Laravel 中存储 32 位二进制文​​件的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66816511/

相关文章:

php - 查询查找靠近我的地方(Google map )

c++ - 如何将二进制输入存储在 C++ 数组中

在 Ubuntu 上创建二进制文件

c++ - 真值表输入生成

php - 重置 ID 自动增量 ? phpmyadmin

php - 岩石上的恶魔

mysql - “Where IN” 是否在标准 SQL 中定义了多个列?

php - Laravel 5:在控制台内核的 Schedule() 函数中使用 Cache::or DB::

php - iframe 中的 laravel 应用程序不断刷新 session

php - 如何获取总数量并将其发送到另一个表(Laravel)