【问题标题】:Getting particular object获取特定对象
【发布时间】:2018-02-26 19:52:01
【问题描述】:

“数据”: "{\"thread\":{\"user_id\":76,\"parent_id\":\"139\",\"item_id\":\"178\",\"comment\":\"s \",\"updated_at\":\"2017-09-18 15:19:24\",\"created_at\":\"2017-09-18 15:19:24\",\"id\":140},\"user\":{\"id\":76,\"name\":\"Kavi\",\"lastname\": \"Arasan\",\"mobile\":\"822-034-1179\",\"email\":\"kayalmanimohana@gmail.com\",\"verified\":0,\"email_token\ ":\"1ATrlUoyWy\",\"created_at\":\"2017-09-15 16:47:59\",\"updated_at\":\"2017-09-18 15:18:57\",\"address\":null,\"city\":null,\"state\":null,\"country\":null,\"pin\":null,\" profile\":null,\"gender\":null,\"street_num\":null,\"provider\":null,\"provider_id\":null,\"is_delete\":null,\"username\ ":\"虚拟\"}}",

我的数据库中有这样的数据对象。如何获取数据线程中存在的用户 ID?我正在使用 laravel

【问题讨论】:

  • 欢迎来到 SO。这只是数据。您甚至没有指定任何需要使用的技术。有人应该如何提供帮助?
  • 我在使用 laravel
  • 好的,我已提交修改您的标签的修改。
  • 虽然这仍然是一个过于宽泛的问题。请做一些研究,展示一些努力和代码,并向它提出更具体的问题。
  • 这就是使用关系数据库存储序列化数据的结果。 :)

标签: php json laravel


【解决方案1】:

@kayal 如果你还在学习,那么这很好,但有时你应该阅读文档

这里是你可以轻松做到这一点的方法

举例

假设表名test

+------------+
| id |  data |
+------------+
| 1  | {...} |
+------------+

假设你有 Model Test.php

然后添加一个受保护的属性$casts它是这个数组中的一个数组添加key => value key是列名,值将是你想要转换的类型,如对象或数组如果我正在使用对象。

namespace App;

class Test extends Model
{
    protected $casts = ['data' => 'object']; // add this property


在您的控制器中

在这种情况下,我使用的是TestController.php

namespace App\Http\Controllers;

use App\Test;

class TestController extends Controller
{

    public function seeUserId()
    {
        $test = Test::find(1); // or your query
        $user_id = $test->data->thread->user_id; // you can access like this this is only example
    }


    public function saveData($data)
    {
        $test = new Test;
        $test->data = $data; // don't use json_encode() just pass any object or array ;
        $test->save();
    }

laravel 文档 :- https://laravel.com/docs/5.5/eloquent-mutators#array-and-json-casting

【讨论】:

    【解决方案2】:

    foreach ($unread as $unr) { $data = json_decode($unr->data,true); $user_id = $data['thread']['user_id'];
    }

    这让一切成为可能

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-23
      • 2017-07-03
      • 2018-08-19
      • 2012-07-20
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多