简体   繁体   English

获取Laravel中Table的最新记录

[英]Get last record of Table in Laravel

I Have a table of projects and reports that reports table save many reports of project in every day. 我有一个项目表和报告,报告表每天都保存许多项目报告。 Now, I want to get last reports date property of project I'm using this code in controller: 现在,我想获取我正在控制器中使用以下代码的项目的上次报告日期属性:

 $res = Project::with(['reports' => function($query){
            $query->orderBy('updated_at', 'DESC')->first();
        }])->get();
        return view ('home',compact('res'));

And in view I have this code: 鉴于我有此代码:

@foreach(Auth::user()->projects as $project)
  @if($res->date == Now())
     <p>hi</p>
 @else
    <p>By</p>
@endforeach

But I get this Error: Property [date] does not exist on this collection instance and return $res in view I give this jason: 但是我得到这个错误: Property [date] does not exist on this collection instance鉴于我给这个杰森的观点而返回了$ res:

{"id":51,"user_id":21,"name":"dff","description":"fff","price":4444,"status":0,"darsad":4,"start_time":"1396-08-18","finish_time":"1396-08-29","created_at":"2017-11-19 08:22:39","updated_at":"2017-11-19 08:22:39","reports":[{"id":20,"user_id":21,"project_id":51,"date":"96\/09\/06","description":"vvvv","created_at":"2017-11-27 11:19:43","updated_at":"2017-11-27 11:19:43"}]}

How can I get last reports of any projects? 如何获得任何项目的最新报告?

Assuming your requirement is just to display the latest single record. 假设您只需要显示最新的单个记录。 This below method can be given a shot. 下面的方法可以尝试一下。

Controller Snippet: 控制器代码段:

$res = Project::orderBy('updated_at', 'DESC')->get();
return view ('home',compact('res'));

Blade Snippet: 刀片片段:

    @foreach ($res as $data)
        @if ($loop->first)
            @if($data->reports[0]->date == Now())
              <p>hi</p>
            @else
              <p>By</p>
            @endif

        @endif
    @endforeach

Hayy...you are trying to compare undefined value because the date is part of reports array in your response. Hayy ...您正在尝试比较未定义的值,因为日期是响应中报告数组的一部分。 So you can't directly access date from your response.Better try to use the below snippet instead of ur blade. 因此,您无法直接从响应中访问日期。最好尝试使用以下代码段代替您的刀片。 It tries to access reports and then access date from reports. 它尝试访问报告,然后访问报告中的日期。

@foreach(Auth::user()->projects as $project)
  @if($res->reports[0]->date == Now())
     <p>hi</p>
 @else
    <p>By</p>
 @endif
@endforeach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM