Deleting relational records

Suppose I have Town model and Customer model

I want to delete Town id 100, but there are several Customer records with FK town_id 100

So in this case user should not be allowed to delete Town id 100 as it will break Customer records.

How can I enable this functionality? (user should be presented with an error message)

Simple if/else statement




records = Look-up customers where town_id = 100  (probably using count)


if (there are some records) 

 add error

else

 call the delete function



Try using the STAT relation http://www.yiiframework.com/doc/guide/database.arr#statistical-query the example can easily be changed…

You should do this at the database level too.

http://www.yiiframework.com/doc/api/CActiveRecord#exists-detail

^better than count() for this case