2016-12-18 36 views
2

我有一個包含所有類別文章帖子的列表。我想在列表中的每個帖子中顯示的類別標籤,我嘗試這樣的:在帖子記錄中獲取類別名稱

<article class="post bg z-depth-1"> 
        <?php foreach ($article_list as $article): ?> 
        <div class="post-img"> 
         <a href="post.html"> 
          <img class="retina" src="{{ asset('image/' . $article->image) }}" width="820" height="500" alt="Post Image"> 
         </a> 
        </div> 
        <div class="post-content"> 
         <div class="post-header center-align"> 
          <div class="tags"> 
           <a href="#">{{ $article->category->title }}</a></div> 
          <h2 class="post-title"><a href="post.html">{{ $article->title }}</a></h2> 
          <div class="date">Posted on {{ Carbon\Carbon::parse($article->created_at)->format('F j, Y') }}</div> 
         </div> 
         <div class="post-entry"> 
          <p>sss</p> 
         </div> 
         <div class="post-footer"> 
          <div class="post-footer-item"> 
           <a href="post.html" class="link"><span class="text">Read More</span> <i class="fa fa-arrow-circle-right"></i></a> 
          </div> 
         </div> 
        </div><!-- .post-content --> 
        <?php endforeach ?> 
       </article><!-- .post --> 

,它給了我錯誤Undefined property: stdClass::$category,我不知道爲什麼,我已經定義每個模型文章和類別的關係。謝謝您的幫助!

在文章模型:

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

在分類模式:

public function article() { 
     return $this->hasMany('App\Article', 'category_id'); 
    } 

控制器:

public function index() { 
     $article_list = Article::all(); 
     return view('article/index', compact('article_list', $article_list)); 
    } 
+0

請出示你的人際關係。 – GabMic

+0

@GrowingDev我已在您的模型中更新了我的問題 –

+0

,請刪除'category_id'字段並嘗試。 – GabMic

回答

0

更改此設置:$物品─>類別 - >標題

爲此:$ article-> () - >標題

當您在模型中定義關係時,您還創建了一個函數,而不是稱爲類別的屬性。

+0

試過這之前,並給了我錯誤'調用undefined方法stdClass :: category()' –

+0

這不是正確的方法。 – GabMic

+0

我很抱歉,錯誤的答案。我相信yoiur解決方案是急於加載:https://laravel.com/docs/5.3/eloquent-relationships# – James

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

在分類模式:

public function article() { 
     return $this->hasMany('App\Article'); 
    } 

控制器:

public function index() { 
     $article_list = Article::all(); 
     return view('article/index', compact('article_list')); 
    } 

這應該現在給你這樣工作。

+0

當你告訴我從兩個模型關係函數中刪除category_id時,我完全是這樣做的,仍然沒有工作 –

+0

這個錯誤總是顯示出'未定義的屬性:stdClass :: $ category' –

+0

請諒解e顯示您的數據庫表的帖子和類別。 – GabMic

相關問題