0

我有一个表 2 具有 am:m 关系的表,我想要的是,当我从其中一个表中删除一行时,我希望连接表中的行也被删除,我的 sql 如下,

表格1

    CREATE TABLE IF NOT EXISTS `job_feed` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `body` text NOT NULL,
  `date_posted` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

表 2

    CREATE TABLE IF NOT EXISTS `job_feed_has_employer_details` (
  `job_feed_id` int(11) NOT NULL,
  `employer_details_id` int(11) NOT NULL,
  PRIMARY KEY (`job_feed_id`,`employer_details_id`),
  KEY `fk_job_feed_has_employer_details_job_feed1` (`job_feed_id`),
  KEY `fk_job_feed_has_employer_details_employer_details1` (`employer_details_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

所以我想要做的是,如果从 table1 中删除 a 行并且 id 为 1 我希望 table 中的行也有这个想法作为关系的一部分。

我想按照我目前拥有的 codeigniters 活动记录类来执行此操作,

public function deleteJobFeed($feed_id)
    {
        $this->db->where('id', $feed_id)
                 ->delete('job_feed');

        return $feed_id;
    }
4

1 回答 1

0

Try something like this (I may have gotten some of the names wrong):

public function deleteJobFeed($feed_id)
{
    //Delete Job Feed
    $this->db->where('id', $feed_id)
        ->delete('job_feed');

    //Get Related Employer information ID from related table
    $query = $this>db->where('job_feed_id', $feed_id)
    ->get('job_feed_has_employer_details');
        if ($query->num_rows() > 0)
        {
            $row = $query->row(); 
            $employer_details_id = $row->employer_details_id;
        }
    //Now you have the employer details id.
    //You can now delete the row you just got, and then use the id to find the row in the employer details table and delete that.
    $this>db->where('job_feed_id', $feed_id)
    ->delete('job_feed_has_employer_details');

    //I'm assuming your third table is called "employer details". You said you had a many to many relationship.
    $this>db->where('employer_details_id', $employer_details_id)
    ->delete('employer_details');

    return $feed_id;
}

Also, if you haven't looked into it, I recommend http://www.overzealous.com/dmz/

It makes handling relationships way easy. Hope this helps.

于 2010-05-24T15:19:36.123 回答