Using the Propel ORM, how would one delete all related records of an object?
Asked Answered
P

1

5

I have a pretty simple Propel question. I'm storing leads in a database. Those leads have one or more community interests. The tables I'm using are named, 'lead', 'community', and a 'lead_communities' join table. What's the best way to delete all of a lead's community interests?

Here are some more details. The Propel schema looks like this:

    <table name="community">
      <column name="id" type="INTEGER" required="true" primaryKey="true" autoIncrement="true" />
      <column name="name" type="VARCHAR" size="255" />
      <column name="address" type="VARCHAR" size="255" />
      etc...


    <table name="lead_communities">
      <column name="id" type="INTEGER" required="true" primaryKey="true" autoIncrement="true"/>
      <column name="lead_id" type="INTEGER" />
      <column name="community_id" type="INTEGER" />
      <column name="created_date" type="DATE" size="4" />
      <foreign-key foreignTable="community" refPhpName="Lead_Communities">
        <reference local="community_id" foreign="id"/>
      </foreign-key>
      <foreign-key foreignTable="lead" refPhpName="Lead_Communities">
        <reference local="lead_id" foreign="id"/>
      </foreign-key>      
    </table>  

    <table name="lead">
      <column name="id" type="INTEGER" required="true" primaryKey="true" autoIncrement="true"/>
      <column name="salutation" type="VARCHAR" size="20" />
      <column name="first_name" type="VARCHAR" size="255" defaultValue="" />
      <column name="last_name" type="VARCHAR" size="255" defaultValue="" />
      <column name="email" type="VARCHAR" size="255" defaultValue="" />
      etc..

Here's how I select the lead from the database:

$lead = LeadQuery::create()->filterByEmail($enauk)->findOne();

So, what I hope to do is something like:

$lead->deleteLeadCommunities();
Poker answered 12/2, 2013 at 23:14 Comment(0)
T
7

Well, the easiest way I can think of without any other context is simply doing a query on the join table with a delete() call:

$numDeleted = LeadCommunitiesQuery::create()
                ->filterByLead($lead)
                ->delete();

Just to be clear, there is no generated method like what you want (deleteLeadCommunities), but you could always write it for convenience, and replace $lead in my example code with $this. So inside Lead.php:

public function deleteLeadCommunities() {
  return LeadCommunitiesQuery::create()
           ->filterByLead($this)
           ->delete();
}
Tifanie answered 12/2, 2013 at 23:46 Comment(1)
Thanks so much. I love your solution.Poker

© 2022 - 2024 — McMap. All rights reserved.