帖子和附件,未定义属性:Illuminate \ Database \ Eloquent \ Collection :: $ name

时间:2015-01-29 22:59:20

标签: laravel-4 eloquent undefined

当我尝试获取附件的名称时这样:

{{$后> attachments->名称}}

我收到以下错误

未定义属性:Illuminate \ Database \ Eloquent \ Collection :: $ name(查看:C:\ wamp \ www \ Sites \ app \ views \ public \ categories \ show.blade.php)

发布模型

class Post extends \Eloquent implements SluggableInterface {

    public function category(){
        return $this->belongsTo('Category');
    }

    public function attachments(){
        return $this->hasMany('Attachment');
    }

}

附件模型

class Attachment extends \Eloquent {

    protected $fillable = ['name', 'type', 'extension', 'user_id', 'post_id', 'size'];


    public function post(){
        return $this->belongsTo('Post');
    }
}

CategoriesController

class CategoriesController extends \BaseController {

    public function show($id, $slug = null)
    {

        $category = Category::find($id);

        $posts = Post::whereCategoryId($category->id)->orderBy('date', 'DESC')->paginate(4);

        return View::make('public.categories.show', compact('category', 'posts'));
    }

}

分类查看

@foreach($posts as $post)
   {{$post->title}} // work fine
   {{$post->body}} // work fine

   {{$post->attachments}} // return this :
       [
         {
            "id":14,
            "name":"29-01-2015-134",
            "type":"image\/jpeg",
            "extension":"jpg",
            "created_at":"2015-01-29 13:04:35",
            "updated_at":"2015-01-29 13:04:35",
            "user_id":1,
            "post_id":134,
            "size":136130
         }
       ]
@endforeach

任何想法?!!!

1 个答案:

答案 0 :(得分:2)

根据您的关系定义,可以有许多附件,这意味着该关系将返回一组模型。你可以只得到第一个:

@if($attachment = $post->attachments()->first())
   {{ $attachment->name }}
@endif

或循环遍历所有附件

@foreach($post->attachments as $attachment)
    {{ $attachment->name }}
@endforeach