We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Error when deleting a record with hasOne relation

Hi

I have these two tables related to each other.

products

$this->hasOne('product_id', '\App\Common\Models\ProductsStats', 'product_id', [
    'alias' => 'Stats'
]);

products_stats

$this->belongsTo('product_id', '\App\Common\Models\Products', 'product_id', [
    'alias' => 'Product'
]);

and in the controller

public function deleteAction($id){

    $product = Products::findFirst($id);
    $product->Stats->delete();
    $product->delete();

}

The problem is that an error occurs if there is no related record in the "products_stats" table. The error only occurs when using hasOne with hasMany does not happen. Is this error normal? Should not it just be ignored?



125.7k
Accepted
answer

I'm not sure why it happens with only hasOne(). My guess would be that with hasOne(), Phalcon maps the related record to a single object. So when you call $product->Stats->delete(), that's on an object. That throws the error because you're trying to do an operation on a non-object. With hasMany(), the related records are all in an array-like object. When you call $product->Stats->delete() in this instance, Phalcon iterates through the array, calling delete() on each object. Since you can loop through a zero length array just fine, no error gets thrown.

In this situation I would set up a foreign key constraint so the stats get deleted automatically whenever the product gets deleted. Typically I do this in the database, but you can also set up the constraint in code when you define the relationship.

https://docs.phalcon.io/3.4/en/db-models-relationships#cascaderestrict-actions



1.5k

Great! Works perfectly, thanks.

Sounds good. Can you accept my answer then, so the thread gets marked as [Solved]?