mysql codeigniter 活动记录 m:m 删除
Posted
技术标签:
【中文标题】mysql codeigniter 活动记录 m:m 删除【英文标题】:mysql codeigniter active record m:m deletion 【发布时间】:2011-02-22 22:10:59 【问题描述】:我有一个表 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;
【问题讨论】:
【参考方案1】:试试这样的(我可能弄错了一些名字):
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/
它使处理关系变得容易。希望这会有所帮助。
【讨论】:
以上是关于mysql codeigniter 活动记录 m:m 删除的主要内容,如果未能解决你的问题,请参考以下文章
如何从 codeigniter 活动记录中的 DATETIME 字段中获取 d-m-Y 格式的日期?
Codeigniter 活动记录类错误与 MySQL 原始查询