Jurik
Jurik

Reputation: 3264

How to delete related record in Yii 2?

I have a table (user) that has related data in another table (order) and the connection between them is one to many.

At this example I see how to create a related data (order). But how can I delete this data (order) when going over the user?

$customer = Customer::findOne(123);
$order = new Order();
$order->subtotal = 100;

// setting the attribute that defines the "customer" relation in Order
$order->customer_id = $customer->id;
$order->save();
$order->id; //e.g. 1

And my approach to delete it would be:

$order = $customer->getOrders()
    ->where(['=', 'id', 1])
    ->all();
$order->delete();

Is this the correct way?

Note: I use constraints.

Upvotes: 1

Views: 3550

Answers (1)

shivani parmar
shivani parmar

Reputation: 334

you can use beforeDelete or AfterDelete() for delete related Table Data

Simple Example :

public function beforeDelete(){
    foreach($this->location_children as $c)
        $c->delete();
    return parent::beforeDelete();
}

Upvotes: 3

Related Questions