帖子和附件,未定义 属性:Illuminate\Database\Eloquent\Collection::$name
posts and attachments, Undefined property: Illuminate\Database\Eloquent\Collection::$name
当我尝试这样获取附件名称时:
{{$post->附件->姓名}}
我收到以下错误
未定义 属性: Illuminate\Database\Eloquent\Collection::$name (视图: C:\wamp\www\Sites\app\views\public\categories\show.blade.php)
Post 型号
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');
}
}
类别控制器
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
有什么想法吗?!!!
根据您的关系定义,可以有许多个附件,这意味着该关系将return一个模型集合。您可以只获得第一个:
@if($attachment = $post->attachments()->first())
{{ $attachment->name }}
@endif
或者遍历所有附件
@foreach($post->attachments as $attachment)
{{ $attachment->name }}
@endforeach
当我尝试这样获取附件名称时:
{{$post->附件->姓名}}
我收到以下错误
未定义 属性: Illuminate\Database\Eloquent\Collection::$name (视图: C:\wamp\www\Sites\app\views\public\categories\show.blade.php)
Post 型号
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');
}
}
类别控制器
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
有什么想法吗?!!!
根据您的关系定义,可以有许多个附件,这意味着该关系将return一个模型集合。您可以只获得第一个:
@if($attachment = $post->attachments()->first())
{{ $attachment->name }}
@endif
或者遍历所有附件
@foreach($post->attachments as $attachment)
{{ $attachment->name }}
@endforeach