Laravel 数据库查询 returns collection of objects - 如何获取要显示的值?

Laravel Database Query returns collection of objects - how do I get the values to display?

我想我的问题有一个简单的解决方案,我只是个初学者 :D

在我的一个控制器上,我有一个相当复杂的数据库请求(见下文),return 是 objects 的 collection 而不是数组(我想我无法执行带有 Eloquent 的请求?)。现在我不知道如何让这些值实际显示在我的 blade 页面中?我是否必须以某种方式将其转换为数组才能做到这一点?

非常感谢!


TagsController.php的一部分:

$tags = DB::table('tags AS ta')
        ->select('ta.name')
        ->join('tag_thread AS tt', 'tt.tag_id', '=', 'ta.id')
        ->join(DB::raw('(select * from threads order by id desc limit 2000) th'), 'tt.thread_id', '=', 'th.id')
        ->groupBy('ta.name')
        ->orderBy(DB::raw('count(ta.name)'), 'DESC')
        ->limit(5)
        ->get();

return $标签:

[
    {
        "name": "javascript"
    },
    {
        "name": "jquery"
    },
    {
        "name": "php"
    }
]

首先使用json_encode()从结果数据中获取json,然后使用json_decode()将json数据转换为数组。所以你的最终结果将是一个多维数组。

$tags=json_decode(json_encode($tags,true),true);

然后您可以将blade中的数据打印为

@foreach ($tags as $tag)
    <div>{{ $tag['name'] }}</div>
@endforeach

在你的 blade 模板中,你可以循环遍历它们:

@foreach ($tags as $tag)
    <div>{{ $tag->name }}</div>
@endforeach

您可以在视图中使用 @foreach 语句来迭代集合

@foreach($tags as $tag)
    <li>{{ $tag->name }}</li>
@endforeach

使用pluck()获取数组中的特定列。

$tags = DB::table('tags AS ta')
        ->select('ta.name')
        ->join('tag_thread AS tt', 'tt.tag_id', '=', 'ta.id')
        ->join(DB::raw('(select * from threads order by id desc limit 2000) th'), 'tt.thread_id', '=', 'th.id')
        ->groupBy('ta.name')
        ->orderBy(DB::raw('count(ta.name)'), 'DESC')
        ->limit(5)
        ->pluck('name');

这将输出如下,只需在 blade

中使用 @foreach ()
[
    "name1",
    "name2",
    "name3",
]

您可以通过两种方式使用集合对象获取值,如下所示-:

  @foreach($tags as $value)

{{$value->name}}

@endforeach

或者你可以使用 toArray 函数。像这样将 toArray 函数放在查询之后

     get()->toArray();

然后使用

    @foreach($tags as $value)

  {{$value['name']}}

     @endforeach