【问题标题】:How to retrieve object value from database stored as json如何从存储为 json 的数据库中检索对象值
【发布时间】:2020-08-09 16:23:31
【问题描述】:

我以json格式存储数据

        $data = [
            'applicant_name' => auth()->user()->name,
            'post_held' => getDesignation(auth()->user()->designation_id)->name,
            'department' => request('department')
        ];

        $leave = new Leave;

        $leave->user_id = auth()->user()->id;
        $leave->data = json_encode($data);

        $leave->save();

如果我想从数据字段中显示申请人姓名,我该如何检索它们?

我在努力——

        $leave = Leave::find($leave_id);

        return $leave->data['applicant_name'];

如果我 dd($leave) 那么它给了我

    "id" => 2
    "user_id" => 7
    "data" => "{"applicant_name":"Mousumi Roy","post_held":"Administrative Officer Judicial","department":"Computer"}"
    "created_at" => "2020-04-25 17:38:25"
    "updated_at" => "2020-04-25 17:38:25"

【问题讨论】:

  • $leave->data 看起来像一个 JSON 字符串,所以您是否尝试过使用 json_decode() 然后访问这些值。
  • 我收到“响应内容必须是实现 __toString() 的字符串或对象,给定的“对象”。” - 如果我喜欢这个错误
  • 所以如果它是一个对象,$leave->data->applicant_name 工作吗

标签: php mysql json laravel


【解决方案1】:

您可以为此使用数组转换,您可以在文档中看到: https://laravel.com/docs/7.x/eloquent-mutators#array-and-json-casting

在你的模型中,使用

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Leave extends Model
{
    protected $casts = [
        'data' => 'array',
    ];
}

那么在你的代码中,你不需要使用 json_decode 或 json_encode,只需:

        $leave = new Leave;
        $leave->data = $data;
        $leave->save();

        $leave = Leave::find($leave_id);
        return $leave->data['applicant_name'];

【讨论】:

    【解决方案2】:

    首先您需要检索对象,例如:$leave,然后通过以下方式访问数据:

    $data = $leave-&gt;data$data = $leave['data']

    但它已编码,因此请尝试使用 $decoded = json_decode($data) 对其进行解码

    最后你可以通过$decoded-&gt;applicant_name访问applicant_name

    【讨论】:

      猜你喜欢
      • 2014-02-09
      • 2019-05-10
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 2017-04-03
      • 2013-10-15
      • 2011-02-01
      • 1970-01-01
      相关资源
      最近更新 更多