问题描述
目前我正在使用
/**
* 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);
并存储在这样的表中
播种机有类似的东西
'binary_number' => str_pad(base_convert(2,STR_PAD_LEFT),
关于在数据库中有 BINARY
类型(如上图所示),apokryfos 建议
我认为 bit 是您在这里需要的,但我不完全确定 Laravel 是否支持它,因此您可能需要使用 DB::raw("b'000000010'")
将数据插入位列
Jarek Tkaczyk 同意 (I'm not fully sure that Laravel supports that
) 部分
拥有位类型字段意味着无论何时插入/更新该字段,都需要使用原始值作为解决方法。 (...)
DB::table('table')->insert(['bit_field' => DB::raw(0)]); // inserts 0
如果可以的话,他建议 OP 更改为 tinyint(对于可以具有值 0 或 1 的列的情况)。
这可能暗示,如果您想通过 Laravel 迁移处理大小为 32 的位,则可能需要使用比 tinyint 大的整数。
所以,如果我想要一个大小为 32 的 int,Alexey Mezenin 指出
你不能这样做,但你可以使用不同类型的整数:
$table->bigInteger()
$table->mediumInteger()
$table->integer()
$table->smallInteger()
$table->tinyinteger()
应该怎么办
$table->char('binary_number',32)->charset('binary');
然后将 32 位二进制数容纳为值以及如何插入/检索此类记录?
解决方法
数据库中的输入应该是无符号整数类型,即 32 位大小或 4 个字节。
$table->unsignedInteger();
因此,保存值应该不是问题,您只需将二进制值切换为使用 bindec()
的十进制值或使用常量方法的简单 SUM。
对于查询部分,假设您想要第三位为 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;