使用 Laravel 将 .JSON 文件保存到数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24501742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save .JSON file to database using laravel
提问by user2480176
I am very new to Laravel and PHP in general, most of what I have worked on has been relative to online tutorials. I know how to save single items like a username or password to my database but I am clueless when it comes to storing an entire file.This is how my database is currently formatted in my migration file:
总的来说,我对 Laravel 和 PHP 非常陌生,我所做的大部分工作都与在线教程有关。我知道如何将用户名或密码等单个项目保存到我的数据库中,但在存储整个文件时我一无所知。这就是我的数据库当前在我的迁移文件中的格式:
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('username');
$table->string('email')->unique();
$table->string('password', 60);
$table->string('remember_token')->nullable();
$table->timestamps();
});
}
Any help is appreciated, let me know is more information about my project is needed.
任何帮助表示赞赏,让我知道需要更多关于我的项目的信息。
Edit:
编辑:
Example of JSON file similar to what I will be using:
类似于我将使用的 JSON 文件示例:
{"Date 1": {
"Item 1": {
"para1": "word",
"para2": 100,
},
"Item 2": {
"para1": "word",
"para2": 100,
},
"Item 3": {
"para1": "word",
"para2": 100,
}
}
"Date 2": {
"Item 1": {
"para1": "word",
"para2": 100,
},
"Item 2": {
"para1": "word",
"para2": 100,
},
"Item 3": {
"para1": "word",
"para2": 100,
}
}}
回答by Scopey
Add this line to your migration file:
将此行添加到您的迁移文件中:
$table->string('json');
Refresh your migrations
刷新您的迁移
php artisan migrate:refresh
Add to your user object:
添加到您的用户对象:
class User extends Eloquent
{
public $json;
}
Set the property as usual (a setter is recommended but not provided in this example)
像往常一样设置属性(建议使用 setter,但在此示例中未提供)
$user = new User;
$user->json = json_encode( array('test-key' => 'test-data' ) );
Save
节省
$user->save();