如何在 CakePHP 组件中使用 TableRegistry?
How to use TableRegistry in CakePHP component?
我是 cakephp 的新手,正在尝试使用 cakephp 版本 4.0.7 创建一个组件。
在组件中,我需要将数据保存在 table 中。我已经关注了这个documentation on inserting data
在组件中,我尝试了以下注册表代码 table
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 has been deprecated. Use
Cake\ORM\Locator\LocatorAwareTrait::getTableLocator() or
Cake\Datasource\FactoryLocator::get('Table')
阅读https://book.cakephp.org/4/en/appendices/4-1-migration-guide.html#orm
并尝试使用 FactoryLocator:
use Cake\Datasource\FactoryLocator;
$productsTable = FactoryLocator::get('Table')->get('Products');
//$productsTable->find()...
或者在组件内部注入 trait class
class MyComponent extends Component{
use Cake\ORM\Locator\LocatorAwareTrait;
public function foo()
{
$ProductsTable = $this->getTableLocator()->get('Products');
}
}
我是 cakephp 的新手,正在尝试使用 cakephp 版本 4.0.7 创建一个组件。
在组件中,我需要将数据保存在 table 中。我已经关注了这个documentation on inserting data
在组件中,我尝试了以下注册表代码 table
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 has been deprecated. Use Cake\ORM\Locator\LocatorAwareTrait::getTableLocator() or Cake\Datasource\FactoryLocator::get('Table')
阅读https://book.cakephp.org/4/en/appendices/4-1-migration-guide.html#orm
并尝试使用 FactoryLocator:
use Cake\Datasource\FactoryLocator;
$productsTable = FactoryLocator::get('Table')->get('Products');
//$productsTable->find()...
或者在组件内部注入 trait class
class MyComponent extends Component{
use Cake\ORM\Locator\LocatorAwareTrait;
public function foo()
{
$ProductsTable = $this->getTableLocator()->get('Products');
}
}