mysql codeigniter活动记录m:m删除
问题描述:
我有一个表有两个有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;
}
答
尝试是这样的(也许是我错了得到一些名字):
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/
它使处理关系的方式很容易。希望这可以帮助。