其中第三个表字段的条件在多对多关系中使用数据映射器


Where condition on third table field in many to many relationship using datamapper

我有 3 张桌子-

users(id,name,dob)
books(id,title,author)
issuedbooks(id,book_id,student_id,issue_date)

用户和书籍之间的关系是多对多的,导致第三表发行书籍。

我的模特是-

class student extends DataMapper{
    var $table="students";
    var $has_many=array(
        "books"=>array(
            "class"=>"book",
            "join_table"=>"issuedbooks",
            "join_self_as"=>"student",
            "join_other_as"=>"book",
            "other_field"=>"students"
        )
    );
}
class book extends DataMapper{
    var $table="books";
    var $has_many=array(
        "students"=>array(
            "class"=>"student",
            "join_table"=>"issuedbooks",
            "join_self_as"=>"book",
            "join_other_as"=>"student",
            "other_field"=>"books"
        )
    );
}

这张表发行的书籍有这样的条目-

id      student_id      book_id  issue_date
1       2               1        2013-07-18 
2       2               4        2013-07-16 
3       1               5        2013-07-18 
4       2               6        2013-07-18

现在我必须找出所有那些由ID为2和issue_date 2013-7-17的学生选择的书籍。

我已经尝试过,但不会得到任何结果。

$student=new student();
$student->get_by_id('2');
$student->books->include_join_fields()->get();
foreach($student->books as $book):

$book->where_join_field($student,'issue_date>',"2013-07-17"(->get((;

    echo $book->title." ".$book->join_issue_date."<br />";
endforeach;

请帮帮我,我哪里出错了?

这是我对这个问题的解决方案,我想这很简单。
而且您不必在多对多表(发行书(中创建 ID 列。
issuedbooks .book_idissuedbooks.student_id必须primary_keys。

class SomeModel extends CI_Model
{
    public function getBooksByStudentIdAndDate($students_id, $date)
    {
        $students_id = (int) $students_id;
        $date = (date('Y-m-d', strtotime($date)) === $date) ? $date : false;
        if( ! $students_id OR ! $date)
            return array();
        $this->db->where('issuedbooks.students_id', $students_id);
        $this->db->where('issuedbooks.issued_date', $date);
        $this->db->select('
            users.name, 
            books.title, 
            issuedbooks.issued_date as date
        ');
        $this->db->join('users','issuedbooks.students_id=users.id');
        $this->db->join('books','issuedbooks.book_id=books.id');
        $this->db->order_by('issuedbooks.issued_date', 'asc');
        return $this->db->from('issuedbooks')->get()->result_array();
    }
}

我会这样做:

$student=new student();
$books = $student->where('id',2)
             ->where_related_book('issue_date','2013-07-17')
             ->get()
foreach($books as $book){
    ...

总的来说,我认为你把你的模型复杂化了一点。只要你遵守标准,你就不需要在你的关系中指出连接表等