0

我有一個表有兩個有am:m關係的表,我可以想要的是,當我從一個表中刪除一行時,我想讓連接表中的行成爲刪除以及,我的SQL是如下,mysql codeigniter活動記錄m:m刪除

表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中刪除了一行,並且ID爲1,那麼我希望表中的那一行也具有該想法作爲關係的一部分。

我想這樣做與codeigniters活動記錄類我目前有此一致,

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

     return $feed_id; 
    } 

回答

0

嘗試是這樣的(也許是我錯了得到一些名字):

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; 
} 

此外,如果你還沒有看過它,我推薦http://www.overzealous.com/dmz/

它使處理關係的方式很容易。希望這可以幫助。