在Laravel中使用-> paginate()时出错 [英] Error when using ->paginate() with Laravel

查看:440
本文介绍了在Laravel中使用-> paginate()时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的论坛上有这个Topic控制器.主题有很多帖子,而帖子属于主题.

So I have this Topic controller on my forum. The Topic has many Posts and the Post belongs to the Topic.

class Topic 
{
    public function posts()
    {
        return $this->hasMany('Post');
    }
}

class Post 
{
    public function topic() 
    {
        return $this->belongsTo('Topic');
    }
}

要获取有关某个主题以及与之相关的所有帖子的信息,我要做:

To get the informations about a Topic and all of the posts related to it, I do:

$query = Topic::where('id', $id)->with('posts');

但是每次我尝试添加时:

But every time I try to add :

$query = $query->paginate(15)

我使用$topic->title,我得到:

Undefined property: Illuminate\Pagination\Paginator::$title

有什么主意吗?谢谢.

哦,如果我使用->get()而不是->paginate(),我没有错误.

EDIT : Oh and if I use ->get() instead of ->paginate() I don't have errors.

推荐答案

paginate(15)调用返回一个Paginator对象,其中包含许多Topic项.如果要获取其中一项的title字段,则需要首先获取其中一项.您可以通过以下方式进行此操作:

The paginate(15) call returns a Paginator object, holding many Topic items. If you want to get the title field of one of these items, you need to get one of them first. You can do this for example via:

$query->first()->title;

更有可能,您将遍历结果并像这样使用它们:

More likely, you will loop through the results and use them like that:

foreach($query as $key => $value)
{
    // do something here, $value contains a Topic object.
    $name = $value->name;
}

这篇关于在Laravel中使用-> paginate()时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆