Sunday, March 13, 2022

[FIXED] in cakephp4 how to access a model within a model

Issue

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
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/



Answered By - Salines

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.