0
votes

Hi I just made a function to save data in multiple tables. Even Though, I followed the instruction in Instruction for Cakephp 3.0

It saves data in only one table.

Please see what i missed.

Thank you

public function saveTest()
{
    $goods = TableRegistry::get('Goods');
    //$data = $this->request->data;
    $data = [
        'brand' => 'brand',
        'name' => 'name',
        'dis_price' => 100,
        'w_price' => 90,
        'line_des' => 'haha',
        'line_w_des' => 'hehe',
        'hash_tag' => 'hoho',
        'price' => 100,
        'good_stock' => [
            'options' => 'asd',
            'stock_count' => 100
    ]];
    Debugger::log($data);
    $entity = $goods->newEntity($data, [
        'associated' => ['GoodsStocks']
    ]);
    Debugger::log($goods->save($entity));
    //Debugger::log('3');
}


public function initialize(array $config)
{
    $this->entityClass('App\Model\Entity\Goods');
    $this->table('goods');
    $this->displayField('name');
    $this->primaryKey('id');
    $this->addBehavior('Timestamp');
    $this->hasMany('GoodsStocks',[
        'alias' => 'Users',
        'foreignKey' => 'good_id',
        'dependent' => true
    ]);
}

Unfortunately It saves the data in only Goods table.

Thank you

1
Where do the instructions say that the property name should be singular, holding a one-dimensional array?ndm
I missed the naming convention and multi-dimensional array. thank you for reminding me of these. but Even though i changed the codes, It still doesn't work.Eric Lee

1 Answers

1
votes

Your array for your GoodStock association should be a lower-underscored version of the association name. Plus, it probably won't be a one-dimensional array thus it's a hasMany association. You can find more information here.

So your code should be moreless as:

$data = [
    'brand' => 'brand',
    'name' => 'name',
    'dis_price' => 100,
    'w_price' => 90,
    'line_des' => 'haha',
    'line_w_des' => 'hehe',
    'hash_tag' => 'hoho',
    'price' => 100,
    'good_stocks' => [
        ['options' => 'asd', 'stock_count' => 100]
    ]
];

I hope you find it useful.

PS: Sorry for any grammar mistakes but English is not my native language ;)