3

How do i access another model within a model in cakephp4.2? The docs on this issue isnt clear to me and i can then run a query on this ? TableRegistry is deprecated now.

 error Unknown method "getTableLocator" called on App\Model\Table\LessonsTable  

//none of these no longer work
in model {

use Cake\ORM\Locator\LocatorAwareTrait;


class LessonsTable extends Table
 {
 ..

  private function  getlessonRevenue(){

  //$clients = $this->getTableLocator()->get('Clients');
  // $cleints = TableRegistry::get('Clients'); 
  // $this->Table = TableRegistry::get('Clients');
   $clients = $this->getTableLocator()->get('Clients');

https://api.cakephp.org/4.0/class-Cake.ORM.TableRegistry.html

atown99
  • 109
  • 12

1 Answers1

5

Try:

<?php
use Cake\ORM\Locator\LocatorAwareTrait; //<------------ add here
class ArchivesTable extends Table
{
  use LocatorAwareTrait; // <--------------------------- and add here
  public function myMethod()
  {
      $clients = $this->getTableLocator()->get('Clients');
  }

and read https://book.cakephp.org/4/en/orm/table-objects.html#using-the-tablelocator

and learn how to use php trait https://www.phptutorial.net/php-tutorial/php-traits/

Salines
  • 5,674
  • 3
  • 25
  • 50
  • Unknown method "getTableLocator" called on App\Model\Table – atown99 Mar 26 '21 at 07:35
  • I go this error with the command use Cake\ORM\Locator\LocatorAwareTrait; Unknown method "getTableLocator" called on App\Model\Table as i already said so above i used this command. – atown99 Mar 26 '21 at 07:37
  • did you load trait? use \Cake\ORM\Locator\LocatorAwareTrait; ? – Salines Mar 26 '21 at 08:37
  • i added more code above to make it clearer and i have no idea why it hasnt worked – atown99 Mar 26 '21 at 09:08
  • it works when i add use LocatorAwareTrait; outside the function. This is a very complicated way to just get a model compared to earlier versions of cakephp? you just had to do this before $articles = TableRegistry::get('Articles'); – atown99 Mar 26 '21 at 23:15
  • 1
    Since 4.3.0, you can also use `fetchTable` method. See: https://book.cakephp.org/4/en/orm.html#quick-example – Ishan Dec 30 '22 at 08:52