【问题标题】:Laravel Pagination in eloquent ORM with()雄辩的 ORM 中的 Laravel 分页 with()
【发布时间】:2016-08-10 22:20:02
【问题描述】:

我在 laravel 中使用了分页,那个时候查询很简单。所以我设法毫无问题地处理它。但这一次,我有一个复杂的查询。

下面是查询:

$data['list'] = User::select('id')
                ->with(array('contacts.contact_fields' => function($query)
                {
                    $query->join('default_contact_method', 'contact_fields.field_type', '=', 'default_contact_method.id')
                          ->where('contact_fields.is_deleted', '=', 0);
                }))
                ->with(array('contacts' => function($query)
                {
                    $query->select('contact_types.type AS type_name')
                          ->join('contact_types', 'contacts.type', '=', 'contact_types.id')
                          ->where('contacts.is_deleted', '=', 0)
                          ->paginate(2);
                }))
                ->where('id', '=', $user_id)
                ->get();

我在with() 中使用了paginate(),因为我想对联系人进行分页,它工作正常。我的问题是在视图端。我无法显示链接。

正在观看:

{{ $list->links() }} // not working
{{ $list[0]->contacts->links() }} // also not working

开启{{ $list[0]->contacts->links() }}

错误信息Call to undefined method Illuminate\Database\Eloquent\Collection::links()

谁能帮帮我?

谢谢!

【问题讨论】:

  • 你解决了吗?我有同样的问题。
  • 你想达到什么目的?对用户的联系人进行分页?

标签: pagination laravel-4


【解决方案1】:

TL;DR:paginate() 外部,在使用 get() 预先加载后手动为内部设置 ->contacts = Paginator::make()

首先,$list->links() 不起作用,因为->get() 返回一个 Collection,而不是 Paginator 实例。因此,要么在整个查询中使用->paginate(),要么手动构造一个 Paginator 实例(查看文档)。

至于contacts->link 不起作用,它可能是两件事之一。您的第一个 with() 具有嵌套关系 (contacts.contact_fields),因此它可能会使用内置的即时加载为您加载联系人。如果不是这样,那么另一个可能的罪魁祸首就是get() 在幕后所做的事情:

public function get($columns = array('*'))
{
    $models = $this->getModels($columns);

    // If we actually found models we will also eager load any relationships that
    // have been specified as needing to be eager loaded, which will solve the
    // n+1 query issue for the developers to avoid running a lot of queries.
    if (count($models) > 0)
    {
        $models = $this->eagerLoadRelations($models);
    }

    return $this->model->newCollection($models);
}

注意newCollection - 所以即使你实际上有一个 Paginator 实例,它实际上也会在后台从项目中创建一个 Collection 实例。

希望这会有所帮助。 :)

【讨论】:

  • 我使用了手动分页。我现在的问题是为什么它仍然显示所有联系人?我可以显示分页的链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 2014-06-22
  • 1970-01-01
  • 2014-10-11
  • 2018-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多