簡體   English   中英

Laravel 4 Eloquent-如何獲取對象屬性

[英]Laravel 4 Eloquent - how to get object properties

我有兩個模型,主題模型和帖子模型。 一個主題可以有多個帖子。

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這就是我的使用方式。 用法 謝謝

將您的latestPost方法更改為:

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

然后使用類似這樣的東西:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM