2

在文档中确切地说,可以像这样保存相关数据:

use App\Model\Entity\Article;
use App\Model\Entity\User;

$article = new Article(['title' => 'First post']);
$article->user = new User(['id' => 1, 'username' => 'mark']);

$articles = TableRegistry::get('Articles');
$articles->save($article);

我在我的代码中尝试了这个,但我得到了错误:

致命错误错误:找不到类“App\Controller\TableRegistry”
文件/Users/mtkocak/Sites/gscrm/src/Controller/BusinessesController.php 行:62

这是我的控制器代码。我怀疑上面的代码对实体模型有效。

    public function add() {
    $business = $this->Businesses->newEntity($this->request->data);
    $record = new Record($this->request->data['Records']);

    $address = new Address($this->request->data['Addresses']);
    $telephone = new Telephone($this->request->data['Telephones']);
    $email = new Email($this->request->data['Emails']);

    $record->business = $business;
    $record->address = $address;
    $record->email = $email;

    if ($this->request->is('post')) {
        var_dump($this->request->data['Records']);
        $records = TableRegistry::get('Records');
        $records->save($record);
        // if ($this->Businesses->save($business)) {
        //     $this->Flash->success('The business has been saved.');
        //     return $this->redirect(['action' => 'index']);
        // } else {
        //     $this->Flash->error('The business could not be saved. Please, try again.');
        // }
    }
    $telephonetypes = $this->Businesses->Records->Telephones->Telephonetypes->find('list');
    $records = $this->Businesses->Records->find('list');
    $businesstypes = $this->Businesses->Businesstypes->find('list');
    $this->set(compact('telephonetypes','business', 'records', 'businesstypes'));
}

这是我的表的 sql 转储:

    CREATE TABLE IF NOT EXISTS `businesses` (
    `id` int(10) unsigned NOT NULL,
  `record_id` int(10) unsigned DEFAULT NULL,
  `businesstype_id` int(10) unsigned DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci AUTO_INCREMENT=1 ;

ALTER TABLE `businesses`
 ADD PRIMARY KEY (`id`), ADD KEY `FK_businesses_records` (`record_id`), ADD KEY `FK_businesses_businesstypes` (`businesstype_id`);

任何帮助表示赞赏。

4

1 回答 1

7

你错过了一个use声明。本书中的所有这些示例都理所当然地认为您从一开始就开始阅读表格部分并使用:

http://book.cakephp.org/3.0/en/orm/table-objects.html#getting-instances-of-a-table-class

use Cake\ORM\TableRegistry;

附言。遵循命名约定时,您不必手动构建实体

于 2014-11-23T22:22:51.120 回答