laravel 如何访问laravel查询结果中的一列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41380781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:01:47  来源:igfitidea点击:

How to access a column in laravel query result

phplaravellaravel-5eloquentlaravel-5.2

提问by Jaskaran Singh Puri

I'm getting an error in my controller Undefined property: Illuminate\Database\Eloquent\Collection::$created_at

我的控制器出现错误 Undefined property: Illuminate\Database\Eloquent\Collection::$created_at

How can I access a column created_atfrom a result of laravel query?

如何created_at从 Laravel 查询的结果访问列?

Controller Code:

控制器代码:

    public function getDashboard() {
        $posts=Post::latest('created_at')->get();
        dd($posts->created_at);
  //      $posts->created_at=Carbon::parse($posts->created_at)->diffForHumans(Carbon::now());
        return view('dashboard',compact('posts'));
    }

It works with findOrFail(some_id)but not with this, why?

它适用于findOrFail(some_id)但不适用于此,为什么?

采纳答案by Alexey Mezenin

get()returns collection, so you need to iterate over it:

get()返回集合,因此您需要对其进行迭代:

foreach ($posts as $post) {
    echo $post->created_at;
}

Or you could use first()to get object instead of collection. In this case this would work:

或者您可以使用first()获取对象而不是集合。在这种情况下,这将起作用:

$post = Post::latest()->first();
$post->created_at;

Also, you don't need to pass created_atto latest(), because this column is defined as default:

此外,您不需要传递created_atlatest(),因为此列已定义为默认值:

public function latest($column = 'created_at')

回答by Amit Gupta

As $postis an instance Collectionyou have to use foreachas:

作为$post一个实例,Collection您必须foreach用作:

foreach ($posts as $post) {
    dd($post->created_at);
}

Or you can use firstto get first object or lastto get last object as

或者您可以使用first获取第一个对象或last获取最后一个对象作为

dd($posts->first()->created_at);

dd($posts->last()->created_at);

Update

更新

Try it as:

试试看:

foreach ($posts as $post) {
    $post->diff_for_humans = $post->created_at->diffForHumans();
}

Then your can access it as:

然后你可以访问它:

foreach ($posts as $post) {
    dd($post->diff_for_humans);
}

回答by meda

when you call get()you can pass an array of fields to select:

当你打电话时,get()你可以传递一个字段数组来选择:

$posts = Post::latest()->get(['created_at']);

then dump to see, what is inside with dd($post)

然后转储看看,里面有什么 dd($post)