2013-03-28 58 views
0

我有「職位」表,它與「類別」表具有多對一的關係。目標是顯示所有帖子及其類別。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 

我是新手,請幫我解決這個問題

回答

0

只需使用::all()代替::with(..)->all()

+0

我改變它到你說的,但仍然是相同的。其他解決方案? –

+0

將外鍵名稱傳遞給關係。並建議:爲數據庫表使用單數名稱 –

2

{{ $ post-> categories-> name}}之前,測試是類別e xists

實施例:

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

@end if 

Aesis。

0

類別是一個數組,因爲您正在使用has_many關係。有很多類別,因此數組返回,所以要訪問它,你必須索引它像一個數組

正確的解決辦法是

$後>類[0] - >名

0

你在使用Laravel 4嗎?首先,在駝峯的情況下,聲明關係的語法是hasMany和belongsTo。檢查它在Laravel documentation

在視圖中,檢查是否類別是空集,即文章是否有其類別:

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

順便說一句,我會用單數形式,模型類的名稱,如郵政和類別,而不是複數形式。在Post類中,我將定義與單數形式的反向一對多關係,以顯示此給定Post的類別表中只有一個條目。

public function category() 
    { 
     return $this->belongsTo('Category'); 
    }