mysql - 通过一条查询删除CAKEPHP 3中所有关联表的数据

标签 mysql cakephp-3.0

我有一个表 products 和一些通过 Product_id 与其连接的表。当产品从产品表中删除时,我想从所有其他表中删除此product_id 的所有行。现在怎样才能以方便的方式做到这一点呢? 我正在尝试如下:

$productTable = [
        'related_products',
        'quantities',
        'products_tags',
        'products_settings',
        'products_details',
        'categories_products',
    ];
    $tableObj = TableRegistry::get('Products');
    $query = $tableObj->query();
    $result = $query->deleteAll()
        ->contain($productTable)
        ->where(['store_id' => $storeId])
        ->execute();

最佳答案

在 Cakephp 中,有一个依赖属性可以从其他表中删除关联的数据。

When the dependent key is set to true, and an entity is deleted, the associated model records are also deleted. In this case we set it to true so that deleting a User will also delete her associated Address.

要使用此功能,只需创建您的关联并添加dependent true。例如

/* In a Table's initialize method. */
$this->hasMany('Comments', [
    'dependent' => true,  /* Add this line */
]);

Cake -> Associations - Linking Tables Together

关于mysql - 通过一条查询删除CAKEPHP 3中所有关联表的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54069150/

相关文章:

mysql - 局部变量和前面的列

python - 如何使 session.expunge_all() 工作以从 SQLAlchemy 中的 session 中分离所有实例?

mysql - 数据库架构,1 个表或 2 个表

mysql - 如何将此 sql 查询转换为 cakephp 3 查询生成器?

php - Cakephp 3 如何使用TestSuite 来测试更新查询?

.net - MySqlCommand 参数不起作用

PHP:从下拉列表中动态获取值?

mysql - 如何从 cakephp 3 中的两个表中获取数据

cakephp - $this->request->allowMethod( ['post' , 'delete' ]) 上不允许的方法;

php - wrk 基准测试工具对于测试最快的 php 框架是否可靠