cakephpcakephp-3.0cakephp-4.x

in cakephp4 how to access a model within a model


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


Solution

  • Try:

    <?php
    
    class ArchivesTable extends Table
    {
    
        use \Cake\ORM\Locator\LocatorAwareTrait; // <------------ add here
    
        public function myMethod()
        {
            $clients = $this->getTableLocator()->get('Clients');
            
            // Since 4.3.0, there is a convenience method
            $clients = $this->fetchTable('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/