php - 字符串中具有特殊字符的 Laravel 种子数据库

标签 php database laravel model eloquent

在 Laravel 中,我试图在我的数据库中添加一些文本字段,这些文本字段中可能包含特殊字符。当我执行 db:seed 时,它说它成功地为数据库播种,但是当我查看我的数据库时,我发现它插入了除特殊字符(在该字段中)之后的文本之外的所有内容。

这是我的种子的样子:

City::create(array(
  'name' => 'Groningen',
  'description' => 'A simple description with a special character é in it, and
   some content that for some reason won\'t be inserted to my database'
));

所以要清楚:'é' 之前的文本被插入到数据库中,但它后面的文本没有。所以我的数据库看起来像:

id   |  name           |  description
-----|-----------------|-------------------
1    |  Groningen      |  A simple description with a special character 

我的城市模型

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class City extends Model {


  /**
   * The database table used by the model.
   *
   * @var string
   */
  protected $table = 'cities';

}

我的城市迁移文件:

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCitiesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cities', function($t) {
            $t->increments('id');

            $t->string('name');
            $t->text('description');

            $t->double('latitude')->nullable();
            $t->double('longitude')->nullable();

            $t->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('cities');
    }

}

还有我的 config/database.php:

return [

    'default' => 'mysql',
    'connections' => [

        'mysql' => [
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'citydb',
            'username'  => 'root',
            'password'  => 'root',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ],
    ],
    // The other Laravel default database.php config

最佳答案

您的描述字段似乎有字符限制。你应该确保它足够长。

但如果不是这种情况,您应该确保您的文件使用正确的编码进行编码,您的数据库使用正确的编码创建,并且与您在 app/config/database.php(或 app/config/local/database.php)。

例如你可以在这个文件中设置:

'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',

并确保您的数据库(和表列设置为 utf8_unicode_ci 并且您放置字符串的文件被编码为 UTF-8

最后一个选项是您的 City Eloquent 模型。你应该确保你不在这里使用任何修改器(例如 str_replacesubstr 或类似的函数,它们可能会修剪数据或以错误的方式修改它 - 例如使用substr 而不是 mb_substr)

关于php - 字符串中具有特殊字符的 Laravel 种子数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26524203/

相关文章:

php - 使用 Jquery 将字符串更改为某种固定格式

php - 是什么导致 'error:1408D172:SSL routines:SSL3_GET_KEY_EXCHANGE:wrong signature type' SSL 错误?

php - 让 MySQL 找出日期间隔与 PHP

database - 配置 Redis 自动使用磁盘

Laravel 避免日期重叠

php - Laravel 5.2 有条件更新数据库

php - 是否可以将 sql 表值分配给 php 中的变量?

Mysql命令无法正常工作

sql - 如果第一个值为空,如何在组合两个值时获取最后一个值?

php - 如何使用 Laravel 的 Mail 函数将变量传递到 Blade 中?