douyu9433 2014-04-08 16:32
浏览 8
已采纳

too long

I have two models, Topic Model and a Post Model. A Topic can have multiple posts.

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

Now to get the latest post for a topic I am doing something like the following

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

}

and then I am getting the latest post attributes as such (for a particular topic)

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

Now , I have tried enough , but it seems that this is not working for me

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

my question is why can't i get the properties of the post model ?

Update.. The topic model looks like this

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';



} 

Update 2 This is how I am using it. Usage thanks

  • 写回答

1条回答 默认 最新

  • dongliu4320 2014-04-08 16:59
    关注

    Change your latestPost method to:

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

    Then use something like this:

    $ptitle = FTopic::find(1)->latestPost()->first()->title;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100