Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 在Laravel中存储32位二进制文件的正确方法_Mysql_Laravel_Binary_Bit_Laravel Migrations - Fatal编程技术网

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

Mysql 在Laravel中存储32位二进制文件的正确方法,mysql,laravel,binary,bit,laravel-migrations,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');

目前我正在使用

/**
 * 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位二进制数,如
00000000000000000000000010
,它们是

并存储在这样的表中

播种机有类似的功能

'binary_number' => str_pad(base_convert(2, 10, 2),32,'0',STR_PAD_LEFT),
关于数据库中的
二进制
类型(如上图所示),建议

我认为这就是您在这里需要的,尽管我不完全确定Laravel是否支持这一点,因此您可能需要使用
DB::raw(“b'000000010')
将数据插入位列

同意(
我不完全确定Laravel是否支持该部分)

具有位类型字段意味着无论何时插入/更新该字段,都需要使用原始值作为解决方法。 (……)

DB::table('table')->insert(['bit\u field'=>DB::raw(0)];//插入0

他还建议,如果可以的话,OP可以改为tinyint(对于一个列,其值可以为0或1)

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

所以,如果我想要一个大小为32的int,指出

您不能这样做,但可以使用不同类型的整数:

$table->bigInteger()
$table->mediumInteger()
$table->integer()
$table->smallInteger()
$table->tinyInteger()
你应该怎么办

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

然后,要将32位二进制数作为值,以及如何插入/检索此类记录?

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

$table->unsignedInteger();
因此,保存值不应该是问题,您只需要使用
bindec()
将二进制值切换为十进制值,或者使用常量方法进行简单求和

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

$query->whereRaw('BIT\u 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\u COUNT('.User::NOTIFICATION\u FRIEND.&NOTIFICATION\u preferences)=1')
->get();
要从表单构建要存储的整数,只需对常量求和

$user->notification_preferences  = User::NOTIFICATION_FRIEND + User::NOTIFICATION_APP;
冗余存储一些容易计算的东西是不“合适的”。仅存储
id
并在需要公式的位版本时使用公式。或者解释裁员的理由。
$user->notification_preferences  = User::NOTIFICATION_FRIEND + User::NOTIFICATION_APP;