We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to delete records on has many to many

I have simple relational Product - ProductCategories - Categories

class Product extends \Phalcon\Mvc\Model
{

    public $id;
    public $sku;
    public $name;

    public function initialize()
    {
        $this->hasManyToMany('id', 'Common\Models\ProductCategories', 'product_id', 'category_id', 'Common\Models\Categories', 'id', array('alias' => 'ProductCategories'));
    }
}
class ProductCategories extends \Phalcon\Mvc\Model
{

    public $id;
    public $product_id;
    public $category_id;

    public function initialize()
    {
        $this->belongsTo('product_id', 'Common\Models\Product', 'id', array('alias' => 'Product'));
        $this->belongsTo('category_id', 'Common\Models\Categories', 'id', array('alias' => 'Categories'));
    }
}
class Categories extends \Phalcon\Mvc\Model
{

    public $id;
    public $section;
    public $name;

    public function initialize()
    {
        $this->hasManyToMany('id', 'Common\Models\ProductCategories', 'category_id', 'product_id', 'Common\Models\Product', 'id', array('alias' => 'ProductCategories'));
    }
}

When I try to delete the related categories in product, ORM delete records from ProductCategories (that's ok) and delete categories from Categories (not ok).

$model = Product::findFirst($id);
$model->ProductCategories->delete()

I just need to delete ProductCategories through relationals, is that possible? Like this:

$productCategories = ProductCategories::find("product_id = '$id'");
$productCategories->delete();


9.3k
Accepted
answer

You can add one relation to ProductCategories and second to Categories

class Product extends \Phalcon\Mvc\Model
{

    public $id;
    public $sku;
    public $name;

    public function initialize()
    {
        $this->hasMany('id', 'Common\Models\ProductCategories', 'product_id', array('alias' => 'ProductCategories'));
        $this->hasManyToMany('id', 'Common\Models\ProductCategories', 'product_id', 'category_id', 'Common\Models\Categories', 'id', array('alias' => 'Categories'));
    }
}

$product = Product::findFirst($id);

// delete only relations
$product->ProductCategories->delete();

// delete with categories
$product->Categories->delete();