You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel中为关联模型添加分页?(根据ID查询场景)

给关联的联系人数据实现分页

你的代码是通过ID查询单个客户并加载其关联的联系人,要实现分页的话,核心是对客户的联系人关联数据进行分页查询(客户本身是单个数据,无需分页)。以下是具体实现步骤:

1. 修改后端控制器代码

原来的with('contacts')会一次性加载所有联系人,我们需要改为通过关联查询构造器调用paginate()方法,同时支持前端传递分页参数:

function customerContact($id)
{
    // 查找指定ID的客户,不存在时返回404
    $customer = Customer::findOrFail($id);
    
    // 对该客户的联系人进行分页,默认每页15条,可通过请求参数perPage自定义
    $contacts = $customer->contacts()->paginate(request('perPage', 15));

    return Inertia::render('Customers/Contacts/Index', [
        'customer' => $customer, // 保留客户基础信息
        'contacts' => $contacts, // 分页后的联系人数据
    ]);
}

关键细节:

  • 用findOrFail($id)替代find($id):客户不存在时自动返回404响应,符合RESTful规范。
  • 调用$customer->contacts()而非$customer->contacts:前者是关联查询构造器,支持链式调用分页方法;后者是已加载的集合,无法直接分页。
  • paginate()参数:默认每页15条,通过request('perPage', 15)允许前端传递perPage参数调整每页数量。

2. 前端(Inertia)处理分页

Laravel返回的分页对象包含data(当前页数据)、current_page(当前页码)、last_page(总页数)、prev_page_url/next_page_url(上下页链接)等字段,直接用这些字段构建分页控件即可:

<template>
  <div class="customer-contacts">
    <h2>{{ customer.name }} 的联系人列表</h2>
    
    <!-- 联系人列表 -->
    <div class="contact-list">
      <div v-for="contact in contacts.data" :key="contact.id" class="contact-item">
        {{ contact.name }} - {{ contact.email }}
      </div>
    </div>

    <!-- 分页控件 -->
    <div class="pagination">
      <InertiaLink 
        v-if="contacts.prev_page_url" 
        :href="contacts.prev_page_url"
        class="pagination-link"
      >
        上一页
      </InertiaLink>
      
      <span class="pagination-info">
        第 {{ contacts.current_page }} 页 / 共 {{ contacts.last_page }} 页
      </span>
      
      <InertiaLink 
        v-if="contacts.next_page_url" 
        :href="contacts.next_page_url"
        class="pagination-link"
      >
        下一页
      </InertiaLink>
    </div>
  </div>
</template>

<script setup>
import { InertiaLink } from '@inertiajs/vue3';

defineProps({
  customer: Object,
  contacts: Object,
});
</script>

前端注意:

  • 联系人数据需从contacts.data中获取,分页对象的data字段才是当前页的列表数据。
  • prev_page_url和next_page_url是Laravel自动生成的链接,通过InertiaLink跳转即可,无需手动拼接参数。

内容的提问来源于stack exchange,提问作者Aleks12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:05:16