CakePHP does not delete the joint table data (belongsToMany)

When I delete an entity which have a belongsToMany association ORM does not delete the joint table data. (Cake v 4.1.7)

$this->SpaceObjects->deleteAll(['type' => 1]);

the setup looks like this:

class SpaceObjectsTable extends Table
    {
        public function initialize(array $config): void
        {
            ...

            $this->belongsToMany('Assets', [
                'foreignKey' => 'space_object_id',
                'targetForeignKey' => 'asset_id',
                'joinTable' => 'assets_space_objects'
            ]);
        ...

class AssetsTable extends Table
{
    public function initialize(array $config): void
    {
        ...

        $this->belongsToMany('SpaceObjects', [
            'foreignKey' => 'asset_id',
            'targetForeignKey' => 'space_object_id',
            'joinTable' => 'assets_space_objects',
        ]);
        ...

DB Table “assets_space_objects”: Id, space_object_id, asset_id

I added Foreign key constraints in the DB and it works, but it bothers me why ORM is not working the way it says in the docs.
What am I doing wrong?

Where in the docs does it say that deleteAll will delete associated records? Looking at the code, it’s an extremely simple query that gets executed by that function, it doesn’t make any attempt to do associations.

If you’re thinking of where the manual says “All dependent associations will be deleted”, that’s only for the delete and deleteMany calls, and only if you have the dependent flag set to true in your association (which you don’t).

Well, I think the docs should mention that deleteAll does not deal with associations. The way it is written now is a bit misleading. Meaning of not triggering beforeDelete/afterDelete events is not that obvious.

dependent flag is true by default in BelongsToMany association

class BelongsToMany extends Association
{
      [...]

/**
     * Whether the records on the joint table should be removed when a record
     * on the source table is deleted.
     *
     * Defaults to true for backwards compatibility.
     *
     * @var bool
     */
    protected $_dependent = true;

    [...]

Thanks anyway! :slight_smile: