在 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_replace
、substr
或类似的函数,它们可能会修剪数据或以错误的方式修改它 - 例如使用substr
而不是 mb_substr
)
关于php - 字符串中具有特殊字符的 Laravel 种子数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26524203/