Shurn the Awesomer
CakePHP3 equivalent of neighbor function in CakePHP2

CakePHP3 equivalent of neighbor function in CakePHP2

Written on Thu, 30 June 2016

Strangely, CakePHP3 doesn't have the neighbour function that CakePHP2 used to have. I thought it was such a useful function. Now that I want to use it, CakePHP3 that I'm using doesn't support it anymore.

I'm trying to use it to get the previous and the next blogpost for my navigation quest. After looking around for solution, I'm inspired by this blog post. I've modified the codes to use entity instead of using it as a model, as it's more fitting to be.

public function neighbours() {
$blogposts = TableRegistry::get("MyBlogPostTable");

$prev = $blogposts->find("all", [
"conditions" => [
"id" => $this->id - 1,
],
])
->first()
;

$next = $blogposts->find("all", [
"conditions" => [
"id" => $this->id + 1,
],
])
->first()
;

return [
"prev" => $prev,
"next" => $next,
];
}

Now, don't criticise my codes yet. Firstly, I assume that ID is always retrieved. Secondly, my ID is already natural number. Thirdly, my ID is auto-incremental and in sequence with time.

If you're going to use a code similar to mine, do adjust it to your use case.