doujilou3903 2014-03-16 19:48
浏览 130
已采纳

Laravel在视图中获取Collection对象

in below code i have Eloquent command and that return Collection object and i can not fetch that into view.

$collection = DB::table('contents')
    ->join('categories', function($join)
    {
        $join->on('categories.id', '=', 'contents.category');
    })
    ->where('contents.id', '=', $id)
    ->get();

thats return single Collecton Object and i do not need to use foreach. how to fetch this collection object in view without usign foreach?

i get error after using this :

echo $collection->title;
{{ $collection->title }}

ERROR:

Trying to get property of non-object
  • 写回答

1条回答 默认 最新

  • duanche2007 2014-03-16 20:08
    关注

    What is a single collection object? You must be talking about a single model? Collections are always an array of models.

    Your query should be like:

    $collection = DB::table('contents')
                    ->join('categories', 'contents.category', '=', 'categories.id')
                    ->where('contents.id', '=', $id)
                    ->first();
    
    echo $collection->title;
    

    passing data to the view can be like:

    $data = array(
       'collection' => $collection
    );
    return View::make('collection', $data);
    

    accessing the data from the template:

    {{ $collection->title }}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法