doushen9863 2014-03-08 15:02
浏览 130

如何使用Laravel将二进制数据插入数据库?

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');
});

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]: 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)

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!

  • 写回答

1条回答 默认 最新

  • dongzhuang6417 2014-06-10 07:32
    关注

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

    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?