0

我有一个数据库,其中Classes, Semesters,UsersVisits(Visits是 and 的连接表Users)Classes的关系是:

UserhasAndBelongsToMany Class(通过 Visits ClassbelongsToSemester

现在我想在活动中查看所有内容(表格有一个字段Visits)我读到了 find 方法的包含选项并尝试了这样的事情:ClassesSemesterSemesteris_active

$option = array(
    "contain" => array(
       "Class" => array(
          "Semester" => array(
                 "conditions" => array("Semester.is_active" => true)
           )
        ),
     ),
     "conditions" => array(
         "Visit.user_id" => $id,
         )
     );

但是有了这个,在一个不活跃的学期中的课程被发现,只有学期不是。

这有什么问题吗?还是有其他方法?

4

2 回答 2

1

现在我有了一个解决方案:我使用joins了 find 方法的选项。

"joins" => array(
         array(
            "table" => "classes_semesters",
            "alias" => "ClassesSemesters",
            "type" => "inner",
            "conditions" => array(
                "Visit.class_id = ClassesSemesters.class_id"        
            )   
        ),
        array(
            "table" => "semesters",
            "alias" => "Semester",
            "type" => "inner",
            "conditions" => array(
                "ClassesSemesters.semester_id = Semester.id"        
            )       
        )
 ),
"conditions" => array(
        "Visit.user_id" => $id,
        "Semester.is_active" => true
),
于 2013-11-19T15:27:25.453 回答
0

当您使用包含时,就像您的情况一样,查询不是直接内连接,即类内连接与学期。首先拉取班级记录,然后会在学期表上进行第二次查询,条件为(其中class_id IN(第一次查询的结果)。所以即使在学期表中没有找到记录,蛋糕仍然会返回找到班级记录。

query 1. $class = select * from classes where bla bla 
query 2. select * from semesters where class_id in (result from query 1) and other conditions bla bla

cake 然后将 2 个查询的结果合并在一起以产生 1 个结果。

于 2013-11-19T13:21:13.113 回答