我看过类似的question,但不幸的是答案不适用于我。
我知道我的对象确实包含了我的数据,但@foreach的内部从未在我的视图中调用过。
这是我的控制器:
$newest_article = $this->article->orderBy('created_at', 'DESC')->first();
$articles = Article::allButFirst($newest_article->id)->orderBy('created_at', 'DESC');
return View::make('site/news/index', compact('newest_article', 'articles'));
我的模型的scopeAllButFirst函数:
public function scopeAllButFirst($query, $id){
return $query->where('id', '<>', $id);
}
最后我的观点是:
@extends('site.layouts.default')
@section('content')
<section id="news-main">
<div class="container">
<!-- all posts wrapper -->
<div class="news-box-wrap js-packery clearfix" data-packery-options='{ "itemSelector": ".news-item"}'>
@foreach($articles as $article)
<div class="col-sm-4 news-item">
<a href="{{{ $article->url() }}}" class="news-box-inner">
<div class="news-box-image-wrap">
@if($article->image->url('tile_landscape'))
<img src="{{{ $article->image->url('tile_landscape') }}}" class="news-box-image">
@endif
<span class="news-box-icon">
<i class="fa fa-align-left"></i>
</span>
</div>
<div class="news-box-bottom">
<div class="news-box-data">
<span class="news-box-cat">News</span>
•
<span class="news-box-time">{{{ $article->date() }}}</span>
</div>
<h3>{{{ $article->title }}}</h3>
<div class="news-box-det">
<span class="news-box-author">{{{ $article->author->username }}}</span>
<span class="news-box-like"><i class="fa fa-smile-o fa-lg"></i> 225</span>
<span class="news-box-comment"><i class="fa fa-comment-o fa-lg"></i> 16</span>
</div>
</div>
</a>
</div>
@endforeach
</div>
@stop
我需要遍历Eloquent对象,因为我必须访问模型类中的一些方法。
作为参考,我正在关注andrewelkins/Laravel-4-Bootstrap-Starter-Site
更新
在我的调试中,我注意到我是否替换了
$articles = Article::allButFirst($newest_article->id)->orderBy('created_at', 'DESC');
与
$articles = Article::all();
我没有这个问题。
答案 0 :(得分:0)
对于那些面临问题的人来说,答案一如既往地在API中。事实证明,您必须调用get()方法才能接收Collection。这就是all()返回的内容。所以只需更改
$articles = Article::allButFirst($newest_article->id)->orderBy('created_at', 'DESC');
到
$articles = Article::allButFirst($newest_article->id)->orderBy('created_at', 'DESC')->get();
解决了这个问题。
希望有所帮助