【问题标题】:How to save belongsToMany data in Cake 3.0?如何在 Cake 3.0 中保存 belongsToMany 数据?
【发布时间】:2015-08-19 21:14:48
【问题描述】:

我是 cakephp 新手。 http://book.cakephp.org/3.0/en/orm/associations.html#belongstomany-associationshttp://book.cakephp.org/3.0/en/orm/saving-data.html#saving-with-associations 上的文档对于像我这样的初学者来说似乎太简短或太高级了。

据我所知,我做了以下事情。

//Table Baskets belongsToMany Apples
//At BasketsTable.php in initialize()
$this->belongsToMany('Apples',[
            'joinTable' => 'apples_baskets'
        ]);

MySQL 中的连接表apples_baskets

+---+---------+----------+
|id |apple_id |basket_id |
--------------------------
|   |         |          |
--------------------------

我已将发布请求数据显示在控制器上:

Array
(
    [id] => 1
    [xyz] => blahblah
    [apples] => Array
        (
            [_ids] => Array
                (
                    [0] => 1
                )

        )

    [amount] => 15000
)

现在当我执行save 时,只有 Baskets 表被更新,连接表保持不变,并且没有抛出错误。

我知道我肯定错过了一些东西,但无法弄清楚。请帮忙!!!

【问题讨论】:

    标签: php cakephp has-and-belongs-to-many cakephp-3.0


    【解决方案1】:

    尝试检查您的Baskets Entity 类是否使其apples 属性_accessible

    <?php
    namespace app\Model\Entity;
    
    use Cake\ORM\Entity;
    
    class Basket extends Entity {
        public $_accessible = [
            'apples', // <-- make sure this is present
        ];
    }
    

    在使用这些新的实体类尝试加载数据(使用Table::newEntity()Table::patchEntity())时,一个非常常见的问题,但由于批量分配,其中一些数据实际上并未保存到实体中保护。

    参考:http://book.cakephp.org/3.0/en/orm/entities.html#mass-assignment

    【讨论】:

      【解决方案2】:

      看这里:http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-belongstomany-associations

      尝试设置$basket-&gt;dirty('apples', true);。这应该告诉 cake 这里有未保存的关联需要处理。

      【讨论】:

        猜你喜欢
        • 2019-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多