如何在CakePHP组件中使用TableRegistry?

如何在CakePHP组件中使用TableRegistry?,cakephp,cakephp-4.x,Cakephp,Cakephp 4.x,我是cakephp新手,正在尝试使用cakephp 4.0.7版创建组件 在组件中,我需要将数据保存在表中。我遵循了这一点 在组件中,我尝试了以下注册表表的代码 use Cake\ORM\Locator\LocatorAwareTrait; class MyComponent extends Component{ public function foo() { $ProductsTable = $this->getTableLocator()->

我是cakephp新手,正在尝试使用cakephp 4.0.7版创建组件

在组件中,我需要将数据保存在表中。我遵循了这一点

在组件中,我尝试了以下注册表表的代码

use Cake\ORM\Locator\LocatorAwareTrait;

class MyComponent extends Component{

    public function foo()
    {
         $ProductsTable = $this->getTableLocator()->get('Products');
    }

}
在输出中,我得到以下异常

Call to undefined method App\Controller\Component\MyComponent::getTableLocator()

如何解决此问题?

CakePHP 4.0.x

$productsTable = \Cake\ORM\TableRegistry::getTableLocator()->get('Products');
来自CakePHP 4.1

Cake\ORM\TableRegistry已被弃用。使用 Cake\ORM\Locator\LocatorAwareTrit::getTableLocator()或 Cake\Datasource\FactoryLocator::get('Table')

阅读

并尝试使用FactoryLocator:

use Cake\Datasource\FactoryLocator;

$productsTable = FactoryLocator::get('Table')->get('Products');

//$productsTable->find()...
或在组件类内部注入特征

class MyComponent extends Component{

    use Cake\ORM\Locator\LocatorAwareTrait;

    public function foo()
    {
         $ProductsTable = $this->getTableLocator()->get('Products');
    }

}

对于第一个在ArrayMakePHP版本4.0.x或4.1.x上对成员函数get()的错误调用,请使用TableRegistry::getTableLocator()->get('Products');