【问题标题】:codeigniter active record where_incodeigniter 活动记录 where_in
【发布时间】:2013-10-16 04:57:50
【问题描述】:

我正在使用 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');  

或者有没有更好的方法来存储和处理信息?

【问题讨论】:

    标签: codeigniter activerecord


    【解决方案1】:
    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 2014-10-19
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 2014-04-05
      • 2012-06-14
      相关资源
      最近更新 更多