【问题标题】:Looping through a collection with an array - Laravel使用数组循环遍历集合 - Laravel
【发布时间】:2020-09-10 08:08:46
【问题描述】:

我有一个使用 eloquent 中的 findMany 方法从数据库中提取的集合。 当我 dd 集合时,它看起来像附加的图像。然后我尝试(在我的刀片中) 循环遍历数组中的每个项目,以便能够打印实际记录中的每个值。

$question = Question::whereIn('id', [23,25])->get();

然后在我的刀片中我正在尝试做:

@foreach ($question as $row => $innerArray)
    @foreach ($innerArray as $innerRow => $value)
        {{$value->question}} //I was expecting "What is your favourite food" here
        @foreach ($value->option as $choice)
            <li>{{$choice}}</li> //I was expecting the list of the options here
        @endforeach 
    @endforeach
@endforeach

我做错了什么?

【问题讨论】:

  • 不应该 {{$value-&gt;question}} 是 {{$value['question']}} 因为是数组而不是对象属性? @foreach ($value-&gt;option as $choice)$value['options'] 和 's' 也一样

标签: php laravel loops laravel-blade


【解决方案1】:

Eloquent 返回的所有多结果集都是 Illuminate\Database\Eloquent\Collection 对象的实例,包括通过 get 方法检索或通过关系访问的结果。 Eloquent 集合对象扩展了 Laravel base collection,因此它自然地继承了许多用于流畅地处理 Eloquent 模型的底层数组的方法。

所有集合也可用作迭代器,允许您像简单的 PHP 数组一样循环它们:

$questions = Question::whereIn('id', [23, 25, ..])->get();

foreach ($questions as $question) {
    echo $question->title; // What is your favourite food
    echo $question->name; // food

    foreach ($question->options as $option) {
         echo $option; // Pizza
    }
}

【讨论】:

  • 谢谢。我实际上有这个,它没有工作。所以我以为我错了,结果发现是别的东西破坏了它。只是为了添加选项,我需要对其进行 json_decode ,因为这是一个存储为字符串的数组,因此必须有效地使用 @foreach (json_decode($question->options) as $option)
  • 对,既然你有一个字符串,那么你必须对其进行解码。然而,Laravel 有比这更优雅的东西。阅读一些关于Attribute Casting
  • 是否可以在没有 get() 方法的情况下进行循环?我正在使用 yajra/laravel-datatables 并希望将查询保留为 eloquent builder 而不是集合实例。
【解决方案2】:

正确的语法是这样的:

@foreach ($question as $q)
    {{ $q->question }} //I was expecting "What is your favourite food" here
     @foreach ($q->options as $choice)
         <li>{{$choice}}</li> //I was expecting the list of the options here
     @endforeach 
@endforeach

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 2014-08-13
    • 2021-09-12
    • 2022-01-27
    • 1970-01-01
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    相关资源
    最近更新 更多