如何使用 Laravel 将二进制数据插入到数据库中? [英] How do I insert binary data into a DB using Laravel?

查看:90
本文介绍了如何使用 Laravel 将二进制数据插入到数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Laravel 4 及其 Eloquent ORM 将二进制数据插入到 PostgreSQL 数据库中.我在迁移中有以下内容:

I'm trying to insert binary data into a PostgreSQL database using Laravel 4 and its Eloquent ORM. I have the following in a migration:

Schema::create('DataBlobs', function($table) {
    $table->increments('Id');
    $table->binary('Data');
});

运行迁移后,我确认它创建了一个 PostgreSQL BYTEA 列.伟大的!所以我把它放在一个数据库播种器函数中:

After running the migration, I've verified that it creates a PostgreSQL BYTEA column. Great! So I put this in a database seeder function:

DB::table('DataBlobs')->delete();
// $d contains the binary data I want to insert into the database.
$d = base64_decode($raw_b64data);
$i = new DataBlob();
$i->Data = $d;
$i->save();

但是,当我运行该播种机时,出现以下错误:

When I run that seeder, however, I get the following error:

SQLSTATE[22021]:字符不在曲目中:7 错误:编码UTF8"的无效字节序列:0x89(SQL:插入DataBlobs"(Data")值(我的控制台尝试的二进制乱码)渲染)

SQLSTATE[22021]: Character not in repertoire: 7 ERROR: invalid byte sequence for encoding "UTF8": 0x89 (SQL: insert into "DataBlobs" ("Data") values (binary gibberish that my console tries to render)

我已经使用 var_dump 和 bin2hex 验证了 $d 实际上是一个包含我想要的数据的二进制字符串,但是从错误来看,Laravel 似乎试图将二进制数据作为 UTF8 字符串而不是作为二进制数据.我已经在谷歌上搜索了一天,我找不到任何关于如何使用 Laravel 将二进制数据插入数据库的示例.任何帮助将不胜感激!

I've validated using var_dump and bin2hex that $d is in fact a binary string that contains the data I want, but from the error, it looks like Laravel is trying to insert the binary data as a UTF8 string instead of as binary data. I've been googling for a day now, and I can't find any examples of how to insert binary data into a database using Laravel. Any help would be appreciated!

推荐答案

您可以使用DB::unprepared($code);或者DB::insert()

You can use DB::unprepared( $code ); or DB::insert()

这篇关于如何使用 Laravel 将二进制数据插入到数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆