【问题标题】:posts and attachments, Undefined property: Illuminate\Database\Eloquent\Collection::$name帖子和附件,未定义属性:Illuminate\Database\Eloquent\Collection::$name
【发布时间】:2015-01-29 22:59:19
【问题描述】:

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

{{$post->附件->名称}}

我收到以下错误

未定义属性: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

有什么想法吗?!!!

【问题讨论】:

    标签: laravel-4 eloquent undefined


    【解决方案1】:

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

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

    或遍历所有附件

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

    【讨论】:

    • 感谢@lukasgeiter 的帮助...您的第一个建议(first() 方法)不起作用!当我使用 first() 这样的 $post->attachments->first()->name 方法时,它返回此错误 尝试获取非对象的属性(视图:C: \wamp\www\Sites\app\views\public\categories\show.blade.php) 我认为这是因为在这种情况下我们有 一对多 关系(post和附件),我真的不知道! ...另一方面,您的第二个建议(遍历所有附件)效果很好!出于某种原因,我不知道为什么 $post->attachments->name 不起作用
    • 不客气。第一个的问题是,如果没有任何附件,它将失败。您需要围绕它包装一个 if 语句(请参阅更新的答案)
    • 再次感谢@lukasgeiter ...是的,没错,更新的答案现在可以工作了。它给出的结果与您的第二个建议(循环)相同……我非常感谢您所做的……
    • 请注意,只有当您没有附件或只有一个附件时,它才会产生相同的结果。对于多个附件,我推荐循环。否则你只会得到第一个。请accept回答:)
    • 非常感谢您的精彩回答。你通过解释这种关系帮助了我很多。 :)
    猜你喜欢
    • 2016-06-02
    • 1970-01-01
    • 2016-07-08
    • 2014-11-23
    • 2017-03-05
    • 2017-02-12
    • 1970-01-01
    • 2018-11-18
    • 2016-09-05
    相关资源
    最近更新 更多