1

「カテゴリ」テーブルと多対 1 の関係を持つ「投稿」テーブルがあります。目標は、すべての投稿とそのカテゴリを表示することです。

テーブル:
投稿: id、content、category_id など
カテゴリ: id、name

これが私のコードです

モデル:

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

has_many 関係を使用しているため、categories は配列です。多くのカテゴリがあるため、配列が返されるため、それにアクセスするには、配列のようにインデックスを付ける必要があります

正しい解決策は

$post->categories[0]->名前

于 2013-04-28T21:39:01.613 に答える
0

::all()代わりに使用するだけです::with(..)->all()

于 2013-03-28T22:41:51.600 に答える