我有「職位」表,它與「類別」表具有多對一的關係。目標是顯示所有帖子及其類別。Laravel雄辯 - 一對多的關係(試圖獲得非客體的財產)
表:
帖子:ID,內容,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
我是新手,請幫我解決這個問題
我改變它到你說的,但仍然是相同的。其他解決方案? –
將外鍵名稱傳遞給關係。並建議:爲數據庫表使用單數名稱 –