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

Proper way to store 32-bit binary in Laravel

目前我正在使用

/**
 * 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: 
        $table->timestamps();

    });
}

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

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

并存储在这样的 table

播种机有类似的东西

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

关于在数据库中输入 BINARY(如上图所示), 建议

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 同意 (I'm not fully sure that Laravel supports that) 部分

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 的整数, 指出

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位二进制数作为值,如何insert/retrieve这样的记录?

数据库中的输入应为无符号整数类型,即 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;