laravel loop over collection

北城余情 提交于 2019-12-14 02:36:00

问题


I have this code:

$data = new Restaurant(array('id' => $restaurant_id));
        $data = $data->waitingtimes();
        foreach($data as $oneTime){
            echo $oneTime->value;
        }
exit;

as you see, I tried to print the value attribute for each $data, but I got empty results.

However, when I do this:

$data = new Restaurant(array('id' => $restaurant_id));
        $data = $data->waitingtimes();
        echo $data->first()->value; exit;

I get results, so the $data absolutely has values in it.

I tried to read the basecollection class documentation here https://github.com/laravel/framework/blob/master/src/Illuminate/Database/Eloquent/Collection.php

but there is nothing about loop.

I also read the conllection class documentation here http://laravel.com/api/source-class-Illuminate.Database.Eloquent.Collection.html#5-73 but there is nothing about loop.


回答1:


replace $data = $data->waitingtimes(); by

$data = $data->waitingtimes()->get();



回答2:


You may also try this:

$data = Restaurant::find($restaurant_id);

This will give you only one Restaurant by it's id and if waitingtimes is a relationship/related model then you may try this (known as eager loading, better than dynamic call):

$data = Restaurant::with('waitingtimes')->find($restaurant_id);

Then you may loop like:

foreach($data->waitingtimes as $waitingtime) {
    echo $waitingtime->value;
}



回答3:


replace $data = $data->waitingtimes(); by

$data = $data->waitingtimes()->get();



来源:https://stackoverflow.com/questions/24371759/laravel-loop-over-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!