【问题标题】:Save .JSON file to database using laravel使用 laravel 将 .JSON 文件保存到数据库
【发布时间】:2014-08-21 12:14:52
【问题描述】:

总的来说,我对 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();
    });
}

感谢任何帮助,如果需要有关我的项目的更多信息,请告诉我。

编辑:

类似于我将使用的 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,
  }
}}  

【问题讨论】:

  • 请给我们一个json文件的例子吗?
  • @Hailwood 请检查我的编辑

标签: php json laravel laravel-4


【解决方案1】:

将此行添加到您的迁移文件中:

$table->string('json');

刷新您的迁移

php artisan migrate:refresh

添加到您的用户对象:

class User extends Eloquent
{
    public $json;
}

像往常一样设置属性(建议使用 setter,但本示例中未提供)

$user = new User;
$user->json = json_encode( array('test-key' => 'test-data' ) );

保存

$user->save();

【讨论】:

  • 感谢您的回答。我对'test-key' => 'test-data' 部分有点困惑。那究竟是在做什么?创建新用户后,如何将我的问题中的示例 JSON 设置为默认值?
  • $user->json = 行正是我在对象上设置 json 的位置。 json_encode 将 PHP 数组转换为 JSON 字符串。根据您的 json 格式,您只需将其分配给 $user->json 属性即可。
猜你喜欢
  • 2016-12-13
  • 2018-03-04
  • 1970-01-01
  • 2020-12-17
  • 2018-09-21
  • 1970-01-01
  • 2017-05-10
  • 2015-10-04
  • 1970-01-01
相关资源
最近更新 更多