Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a random row in CakePHP 3.0?

I'm trying to retrieve a random row with CakePHP 3.0 RC-1, I've looked into the docs.

Using what I had from CakePHP 2.X and putting that as a starting point for getting a random row in CakePHP 3.0 RC-1. However, this is apparently not doing it for Miss Cake:

$result = $this->Game->find('all')
            ->order('rand()')
            ->limit(1);

The result yields nothing. There is data in the database, and I am able to retrieve single records. (I.e $this->Game->get(20) works like it should).

like image 301
Coreus Avatar asked Feb 05 '15 15:02

Coreus


People also ask

How can I get data from database in cakephp?

To view records of database, we first need to get hold of a table using the TableRegistry class. We can fetch the instance out of registry using get() method. The get() method will take the name of the database table as argument. Now, this new instance is used to find records from database using find() method.

How can I print last query in cakephp 3?

$post = $this->Posts->get($id, [ 'contain' => ['Postmeta'] ]); echo "<pre>"; print_r(debug($post));die; It will show all result along with sql query syntax. Here we are using debug for show result along with sql query.

How can I order in cakephp?

To apply ordering, you can use the order method: $query = $articles->find() ->order(['title' => 'ASC', 'id' => 'ASC']); When calling order() multiple times on a query, multiple clauses will be appended. However, when using finders you may sometimes need to overwrite the ORDER BY .

How can I get last executed query in cakephp?

Add below line in your model where you want print query. $last_query = $ this ->ModelName->getLastQuery(); As we have saved last executed query in variable $last_query then use this to print last executed query.


1 Answers

Just use "first" for getting the first result:

$result = $this->Game->find('all')
        ->order('rand()')
        ->first();

Alternatively, you can make it work like get() in that it will return an exception if no results are found:

$result = $this->Game->find('all')
        ->order('rand()')
        ->firstOrFail();
like image 145
José Lorenzo Rodríguez Avatar answered Sep 21 '22 13:09

José Lorenzo Rodríguez