Delete relation from junction table

Hi,

So I went through the yii2 guide to create relations via a junction table.

Now I want to delete only the relation from the junction table and keep the records in the two other tables.

What I have is this code:

class Order extends ActiveRecord
{
    public function getOrderItems()
    {
        return $this->hasMany(OrderItem::className(), ['order_id' => 'id']);
    }

    public function getItems()
    {
        return $this->hasMany(Item::className(), ['id' => 'item_id'])
            ->via('orderItems');
    }
}

I have created two tables for Orders and Items and a junction table called Order_items that has two columns holding order_id and item_id. Constraints have been created using cascading properties.

How do I go about deleting the relations without deleting the records?

Hi @WalidBaccari, welcome to the forum.

The straight answer is simple : delete the methods that define the relations. To be specific, delete getOrderItems method then orderItems relation will be deleted, and delete getItems method then items relation will be deleted.

But I’m afraid this is not the exact answer that you want.

If you want to delete only orderItems relation and keep the items relation , then you could use viaTable instead of via in getItems method.

And, in the first place, I couldn’t think of a good reason to delete the relations while keeping the tables. Could you explain why you want to delete them?

Hi @softark, thanks for the reply.

I did not explain myself properly, I’m afraid.

I want to keep the relations in the models. I only want to delete the record in the database that links an item A to order B (i.e. the record from the Order_items junction table) without deleting said item nor said order.

The problem that I had was that when I call actionDelete with cascading foreign key constraints, the item is deleted along with the junction table record.

I found that my mistake is that I was calling actionDelete in ItemController.

After creating an OrderItemController, I am able to delete the orderItem from the database without deleting the other two records.

I hope this is the right way to do this.

Aha, I’m very sorry that I misunderstood.
So you just want to delete a certain order_item record to unlink the related Order and Item without touching order and item records.

Yes, it is.

Or you may do it like this:

$orderItem = OrderItem::findOne(['order_id' => $order_id, 'item_id' => $item_id]);
if ($orderItem) {
    $orderItem->delete();
}

In fact, deletion of a record is executed in the model layer.

ItemController::actionDelete() calls Item::delete(), not OrderItem::delete(). So it is a record in item table that is deleted at first, and then the related record of order_item is automatically deleted by DELETE_CASCADE constraint.

Thanks a lot for your help.
Much appreciated.