codeigniter活动记录where_in

时间:2013-10-16 04:57:51

标签: codeigniter activerecord

我正在使用codeigniter 2xx。 Mysql表:

create table hobby (
id int,
school varchar,
classes varchar,
basketball text,  {12,15,17...}
football text,  {12,18,20...}
swimming text {11,15,....}
);

我打算将学生ID作为序列化(数组(整数))存储在mysql表字段中,如篮球,足球和游泳。
如果他使用codeigniter活动记录方法加入任何爱好或超过1个爱好,但我想找到一个特定的班级学生ID(例如12)。以下是我的代码:

$this->db->select('basketball','football','swimming');
$this->db->or_where('school', $data)->where('classes', $classid)->where_in($student_id, 'basketball');
$this->db->or_where('school', $data)->where('classes', $classid)->where_in($student_id, 'football');
$this->db->or_where('school', $data)->where('classes', $classid)->where_in($student_id, 'swimming');
$query = $this->db->get('hobby');  

或者有更好的存储方式吗?处理信息?

1 个答案:

答案 0 :(得分:0)

CREATE TABLE `student_hobby` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `student_id` INT(11) DEFAULT NULL,
  `hobby_id` INT(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

CREATE TABLE `hobby` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(500) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

设置爱好学生:

$this->db->insert('student_hobby', array('student_id' => 12, 'hobby_id' => 1));

选择有一个或多个爱好的学生:

$this->db->select('student.*, hobby.name');
$this->db->from('student_hobby');
$this->db->where('studend_id', 12);
$this->db->join('hobby', 'hobby.id = student_hobby.hobby_id');
// join to your existing student table. Fields `school` and `class` should be in `student` table.
$this->db->join('student', 'student.id = student_hobby.student_id');
$result = $this->db->get();

if($result->num_rows()) {
      // if student has one or more hobbies
}