【问题标题】:How to attach two fields in json response array in Laravel如何在 Laravel 的 json 响应数组中附加两个字段
【发布时间】:2021-05-22 02:02:21
【问题描述】:

我需要将 start_datestart_time 附加到响应中的一个字段中,如 json 数组中的 start = start_date + start_time,这就是我显示 json 数组的方式

我也需要在所有其他字段中显示为 start : "2021-02-18 12:32:00"

这是我的控制器功能

public function calendar(Job $job)
{

    $user = auth()->user();
    $calendar= $job->where('user_id',$user->id)->get();

    return response()->json($calendar);

}

【问题讨论】:

    标签: php arrays json laravel concatenation


    【解决方案1】:

    您可以使用map() 函数循环并可以像这样添加新密钥

    public function calendar(Job $job)
    {
    
        $user = auth()->user();
        $calendar = $job->where('user_id', $user->id)->get();
    
        $calendar->map(function($row){  
            return $row->start = $row->start_date . ' ' . $row->start_time;
        });
    
        return response()->json($calendar);
    }
    

    【讨论】:

    • 这不起作用 ;( 我得到了和以前一样的响应 json 数组,没有任何错误
    • 现在响应附加了start_dateend_date 这是它如何显示[ "2021-02-18 12:32:00", "2021-02-18 07:32:00", "2021-03-01 11:44:00" ] 但我需要显示为start :“2021-02-18 12:32:00”与所有其他字段
    • 我仍然得到相同的[ "2021-02-18 12:32:00", "2021-02-18 07:32:00", "2021-03-01 11:44:00" ] ;(
    • @Jareer 我已经对此进行了测试,它可以按预期工作可能是您做错了什么
    • 抱歉@Kamlesh,您的代码有效,问题出在模型中,我必须在 Job 模型中添加 protected $visible = ['start']; 并且它有效,非常感谢!
    【解决方案2】:

    我终于可以通过添加以下代码来解决上述问题

    控制器功能

    public function calendar(Job $job)
    {
    $user = auth()->user();
    
    $calendar = $job->where('user_id',$user->id)->get();
    
    $calendar = $calendar->map(function ($post) {
        $post['start'] =  $post->start_date . ' ' . $post->start_time;
        $post['end'] =  $post->end_date . ' ' . $post->end_time;
        // unset($post['name']);
        return $post;
    });
    
    return response()->json($calendar);
    }
    

    型号

    protected $visible  = ['start','end'];
    

    结果

    【讨论】:

      【解决方案3】:

      在您的 Job 模型中,您可以使用 $append 并为其创建和属性,然后它将始终是模型结果的一部分:

      
      class Job extends Model
      
          ...
      
          /**
           * The accessors to append to the model's array form.
           *
           * @var array
           */
          protected $appends = [
              'start',
          ];
      
          ...
      
          public function getStartAttribute()
          {
              return $this->start_date . $this->start_time;
          }
      
          ...
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-10
        • 2018-07-29
        • 1970-01-01
        • 2020-12-06
        • 2018-10-13
        • 1970-01-01
        • 2016-04-14
        相关资源
        最近更新 更多