1
votes

Hi need your help to understand some feature in CakePHP.

I have a SQL Table : user. I generate with bake the Model : UserTable.

In the action home() of my UsersController, i have this :

$t_Results = TableRegistry::get('User')->findByLogin('jdupont')->execute()->fetchAll('assoc');
debug($t_Results);

The query is generated by Cake and this code works well.

My question are :

  • Must i create the function findByLogin inside the Model or not ?
  • Is my code correct ?

Thanks for the help ;)

2
Yes you can create a findByLogin in your model - Tartempion34
Thanks, i had just generate my model file, i wrote anything inside and it works, so why create the function ? What is the best practice ? Thanks. - Cotral Lab

2 Answers

1
votes

Yes you can create a findByLogin in your model but you don't have to.

Your code works but doesn't respect conventions. In CakePHP 3 SQL tables are singular lowercase, Table files has upper first letter and plural suffixed by Table, Controllers are plural first letter upper and suffixed by Controller.

If you follow these conventions in your controller you can do this:

$t_Results = $this->Users->findByLogin('jdupont')->execute()->fetchAll('assoc');
debug($t_Results);

You don't have to use ->execute(). Query objects are lazily evaluated, execute will be called when you will use the request.

1
votes

One of the quickest ways for you to check if your code is correct is to actually run it and see if it returns what you expect.

findByLogin() is a Cake dynamic finder so you don't need to define this method as Cake dynamically does this for you. You can prefix any camel-cased column name with findBy to query a table using that column.

You can use it like this:-

$t_Results = $this->Users->findByLogin('jdupont')->first();