【发布时间】:2021-12-30 07:19:12
【问题描述】:
我遇到了一个问题,即以下代码仅在测试中失败,而在浏览器中表现正确。
代码应为 Eloquent 集合提供 CursorPaginator 并将其作为 JSON 返回。
测试代码:
public function testMoreNotesAreReturnedIfRequested()
{
$item = Item::factory()->has(Entry::factory()->for($this->user)->count(6))->create();
// Get page one of paginator, and request page 2 using the URL it returns
$response = $this->actingAs($this->user)->json('get',"/items/{$item->id}/notes/more");
$next = $this->actingas($this->user)->json('get',$response->decodeResponseJson()['next_page_url']);
$next->assertJson(fn (AssertableJson $json) => $json
->has('data')
->has('paginator'));
}
上述失败,但有以下异常:
光标分页项目时仅支持数组和对象。
我已确认在第 1 行中创建了 6 个条目,并且按照谷歌搜索问题时的建议,它们都有不同的毫秒创建时间。
有什么想法吗?
控制器代码:
return $item->entries()
->latest()
->with(['content','user'])
->cursorPaginate(5)
->withPath("/items/$item->id/notes/more")
->through( static function ($item) use ($request) {
$item->setAttribute('can_edit',$request->user()->can('update',$item->content));
$item->setAttribute('can_delete',$request->user()->can('delete',$item->content));
return $item;
});
编辑 - 测试每次都失败,而浏览器只有在集合中的项目数为 6、7、16 或 17 时才会失败。我现在更加困惑。
【问题讨论】:
-
阅读here中的红框,我认为这不是错误,是您没有使用
order by...。阅读文档以便您不要浪费时间和精力尝试解决可能会损害您的心理健康的问题。 -
@matiaslauriti 是 'latest()' 而不是 'orderBy("created_at","desc")' 的别名?
-
是的,但如果我不感到困惑,您应该使用
id而不是created_at。无论哪种方式,您是否尝试手动写入->orderBy('created_at', 'desc')并查看是否有效?