Laravel:抓取嵌套项

时间:2018-08-16 21:35:27

标签: laravel vue.js

我正试图从类似的收藏中获取一件物品

[
{
"id": 17,
"corretora_id": 1,
"user_id": 2,
"order": null,
"nome": "Johnny English",
"telefone": "(11)0070-0070",
"celular": "(00)70070-0700",
"email": "j@mi7.uk",
"obs": "Lorem ipsum",
"img_lead": "1534353433.png",
"created_at": "2018-08-15 17:17:14",
"updated_at": "2018-08-15 21:30:48",
"atendimentos": [
    {
        "id": 22,
        "lead_id": 17,
        "dataAgendamento": "2018-08-16 09:00:00",
        "user_id": 2,
        "comentarios": "Alea jacta est",
        "created_at": "2018-08-15 20:48:07",
        "updated_at": "2018-08-15 20:48:07"
    }
]
},

...

这将返回一个变量$ leads witch在我的刀片页面上通过foreach循环。看起来像是一条垂直的时间线,如下所示:

 Johnny English
Fixo: (11)0070-0070   Celular: (00)70070-0700

[{"id":22,"lead_id":17,"dataAgendamento":"2018-08-16 09:00:00","user_id":2,"comentarios":"Realmente \u00e9 o homem mais burro do mundo. QUer um plano de sa\u00fade para agentes secretos em nome de 007.\nPediu pra ligar amanh\u00e3","created_at":"2018-08-15 20:48:07","updated_at":"2018-08-15 20:48:07"}]

我只需要显示“ comentarios”项,但是语法{{$ lead-> atendimentos-> comentarios}}无效。 它显示了我编码的原因:{{$ lead-> atendimentos}}

让我展示我的控制器部分代码:

public function index()
    {
        $user = Auth::user();
        $corretora = Corretora::where('id', '=', $user->corretora_id)->first();
        $leads = Lead::where('corretora_id', '=', $corretora->id)
            ->where('user_id', '=', $user->id)
            ->orderBy('created_at', 'desc')
            ->with('atendimentos')
            ->get();
            // return $leads;
        return view('layouts.atendimentos.index')->withLeads($leads);
    }

...和刀片部分:

 <div class="col-6">
            @if($leads->isEmpty())
                    Não há trabalho pra você hoje!
            @endif
            @foreach($leads as $lead)
                <atendimento 
                id={{ $lead->id }} 
                image={{ asset('images/' . $lead->img_lead) }} 
                nome="{{ $lead->nome }}" 
                email="{{ $lead->email }}" 
                telefone="{{ $lead->telefone }}" 
                celular="{{ $lead->celular }}" 
                obs="{{ $lead->obs }}" 
                comentarios="{{ $lead->atendimentos }}"></atendimento>
            @endforeach
        </div>

谢谢!

1 个答案:

答案 0 :(得分:1)

根据您的集合,$lead->atendimentos是一个对象项的数组。因此,要访问comentarios值,您需要使用索引0。

在这种情况下,它变成

{{ count($lead->atendimentos) > 0 ? $lead->atendimentos[0]->comentarios : 'No comentarios' }}