0

我正在使用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 表字段中,如篮球、足球和游泳。
我想找出一个特定的班级学生ID(例如12),如果他使用codeigniter活动记录方法加入了任何爱好或超过1个爱好但卡住了。下面是我的代码:

$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');  

还是有更好的方法来存储和处理信息?

4

1 回答 1

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

选择有 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
}
于 2013-10-16T08:07:04.590 回答