将控制器中的值设置为关联模型,保存在cakephp中

时间:2016-08-24 16:52:20

标签: cakephp cakephp-3.2

我有'seller_businesses table and seller_business_categories`表。我使用单一表单为卖家和卖家_企业保存价值。

表单就像

<?= $this->Form->create() ?>
<?= $this->Form->input('company_name') ?>
<?= $this->Form->input('logo', ['type' => 'file']) ?>
<?= $this->Form->input('seller_business_categories.category_id') ?>
<?= $this->Form->button('Submit', ['type' => 'submit']) ?>
<?= $this->Form->end() ?>

seller_business_categories有一列seller_id,我必须在其中保存登录的用户ID。

我知道要将值保存到控制器中的表seller_businesses,如

$seller_business = $this->SellerBusinesses->newEntity();
$seller_business->seller_id = $this->Auth->user('id');
$this->SellerBusinesses->patchEntity($seller_business, $this->request->data, [
  'associated' => ['SellerBusinessCategories']
]);

但是如何将默认值保存到控制器中的关联模型SellerBusinessCategories

1 个答案:

答案 0 :(得分:0)

你需要建立关系

SellerBusinessCategorie.php MODEL

public function initialize(array $config)
    {
        parent::initialize($config);

        $this->table('seller_business_categories');

        $this->hasMany('seller_businesses', [
            'foreignKey' => 'seller_id'
        ]);
    }

SellerBusinesses.php MODEL

public function initialize(array $config)
        {
            parent::initialize($config);
    $this->belongsTo('seller_business_categories', [
                'foreignKey' => 'category_id',
                'joinType' => 'INNER'
            ]);

}

控制器

 $seller_business = $this->SellerBusinesses->newEntity();
    $seller_business->seller_id = $this->Auth->user('id');
    $this->SellerBusinesses->patchEntity($seller_business, $this->request->data]);

现在尝试......有效