Laravel 4 帖子和附件,未定义属性:Illumb\Database\Eloquent\Collection::$name
当我尝试获取附件的名称时,如下所示: {{$post->attachments->name} 我得到以下错误 未定义的属性:Illumb\Database\Eloquent\Collection::$name(视图:C:\wamp\www\Sites\app\views\public\categories\show.blade.php) 后期模型Laravel 4 帖子和附件,未定义属性:Illumb\Database\Eloquent\Collection::$name,laravel-4,eloquent,undefined,Laravel 4,Eloquent,Undefined,当我尝试获取附件的名称时,如下所示: {{$post->attachments->name} 我得到以下错误 未定义的属性:Illumb\Database\Eloquent\Collection::$name(视图:C:\wamp\www\Sites\app\views\public\categories\show.blade.php) 后期模型 class Post extends \Eloquent implements SluggableInterface { public fu
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 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
有什么想法吗 根据您的关系定义,可以有许多附件,这意味着关系将返回一组模型。您可以只获取第一个:
@if($attachment = $post->attachments()->first())
{{ $attachment->name }}
@endif
或在所有附件上循环
@foreach($post->attachments as $attachment)
{{ $attachment->name }}
@endforeach
感谢@lukasgeiter的帮助…您的第一个建议(first()方法)无效!!当我使用像$post->attachments->first()->name这样的first()方法时,试图获取非对象的属性(视图:C:\wamp\www\Sites\app\views\public\categories\show.blade.php)时,它会返回这个错误,我想这是因为在这种情况下我们有一对多的关系(post和attachments),我真的不知道。。。另一方面,您的第二个建议(在所有附件上循环)工作正常!!出于某种原因,我不知道为什么$post->attachments->name不起作用,不客气。第一个的问题是,如果没有任何附件,它将失败。你需要用一个if语句(参见更新的答案)再次感谢@lukasgeiter…是的,没错,更新的答案现在起作用了。它给出了与你的第二个建议(循环)相同的结果…我真的很感激你所做的…注意,只有当你没有或只有一个附件时,它才会产生相同的结果。对于多个附件,我建议使用循环。否则你只能得到第一个。请回答:)非常感谢你的回答。你解释了这段关系,帮了我很多忙。:)