2014-04-08 24 views
0

我有兩個模型,主題模型和郵政模型。主題可以有多個帖子。Laravel 4雄辯 - 如何獲得對象屬性

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

我們得到最新帖子的題目我做類似如下的

public function latestPost() 
{ 
    return $this->posts()->where('f_topic_id',"=",$this->id)->take(1); 

} 

,然後我得到的最新帖子屬性本身(對特定主題)

{{$topic->latestPost()->first()['title']}} 

現在,我已經嘗試過了,但似乎這不適用於我

{{$topic->latestPost()->first()->title}} 

我的問題是爲什麼我無法獲得帖子模型的屬性?

更新.. 主題模型看起來像這樣

class FTopic extends Eloquent { 
    protected $fillable =['topictitle','topicdescription']; 

    public function forumCategory() 
    { 
     return $this->belongsTo('FCategory'); 
    } 

    public function user() 
    { 
     return $this->belongsTo('User'); 
    } 

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

    public function latestPost() 
    { 
     return $this->posts()->where('f_topic_id',"=",$this->id)->take(1); 

    } 




    public $rules = [ 
     'topictitle' => 'required|min:10', 
     'topicdescription' => 'required|max:10' 
    ]; 

    public $errors; 

    public function isValid() 
    { 
     $validation = Validator::make($this->attributes, $this->rules); 
     if($validation-> passes()) 
      return true; 
     $this->errors = $validation->messages(); 
     return false; 
    } 







    protected $table = 'ftopics'; 



} 

更新2 這是我如何使用它。 Usage 感謝

+0

凡'latestPost'聲明,什麼是'$這個 - >帖子() '? –

+0

@ WereWolf-TheAlpha:我已經更新了這個問題。 – Gagan

回答

0

更改latestPost方法:

public function scopeLatestPost($query) 
{ 
    return $this->posts()->orderBy('id', 'desc'); 
} 

然後使用這樣的事情:

$ptitle = FTopic::find(1)->latestPost()->first()->title; 
+0

我收到此錯誤消息:試圖獲取非對象的屬性 – Gagan

+0

不幸的是,有一個錯字,更新它,再試一次: - –

+0

沒有..我仍然收到相同的消息。請注意,我已經更新了錯誤發生頁面的快照問題。謝謝 – Gagan