1

我有与“类别”表具有多对一关系的“帖子”表。目标是显示所有帖子及其类别。

表:
帖子:id、content、category_id 等
类别:id、名称

这是我的代码

楷模:

class Posts extends Eloquent
{
    public static $table = 'posts';

    public function categories()
    {
        return $this->belongs_to('Categories');
    }
}

class Categories extends Eloquent
{
    public static $table = 'categories';

    public function posts()
    {
        return $this->has_many('posts');
    }
}

我的控制器

public function get_posts()
{
    $posts = Posts::with('categories')->all();

    return View::make('admin.posts')
        ->with('title', 'Posts')
        ->with('posts', $posts);

}

我的观点

@foreach($posts as $post)
        <tr>
            <td>{{ $post->title }}</td>
            <td>{{ $post->categories->name }}</td>
            <td><small> {{$post->updated_at}} </small></td>
            <td>
                <button>
                    {{HTML::link_to_route('edit_post','Edit',array($post->id))}}
                </button>
                {{Form::open('admin/delete','Delete')}}
                {{Form::hidden('id', $post->id)}}
                <input type="submit" name="edit_post" value="Delete"/>
                {{Form::close()}}
            </td>
        </tr>
@endforeach

错误:

Error rendering view: [admin.posts]
Trying to get property of non-object

我是新手,请帮我解决这个问题

4

4 回答 4

2

{{ $post->categories->name }} 测试之前的类别存在

例子:

@if( ! empty($post->categories))
    <td>{{ $post->categories->name }}</td> 
@else

@end if

埃西斯。

于 2013-03-29T14:13:56.837 回答
0

只需使用::all()而不是::with(..)->all()

于 2013-03-28T22:41:51.600 回答
0

你在使用 Laravel 4 吗?首先声明关系的语法是hasMany和belongsTo,在骆驼的情况下。在Laravel 文档中查看

在视图中,检查类别是否为空集合,即帖子是否有其类别:

@if($post->categories->count())
    <td>{{ $post->categories->name }}</td>
    ...
@endif

顺便说一句,我会使用单数形式作为模型类名称,例如 Post 和 Category 而不是复数形式。在 Post 类中,我将使用单数形式定义反向一对多关系,以显示该给定 Post 的类别表中只有一个条目。

public function category()
    {
        return $this->belongsTo('Category');
    }
于 2014-09-25T04:28:35.037 回答
0

类别是一个数组,因为您正在使用 has_many 关系。有很多类别,因此返回一个数组,因此要访问它,您必须像数组一样对其进行索引

正确的解决方案是

$post->类别[0]->名称

于 2013-04-28T21:39:01.613 回答