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).
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.
$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.
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 .
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With