首页 文章

相关模型中的CakePHP条件

提问于
浏览
0

我有一个 ClassesSemestersUsersVisits 的数据库( VisitsUsersClasses 的连接表)关系是:

User hasAndBelongsToMany Class (通过访问 Class belongsTo Semester

现在我想查看所有 VisitsClasses 在一个活动 SemesterSemester 表有一个字段 is_active )我读了一个关于find方法的包含选项,并试过这样的事情:

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

但是有了这个,找到了一个不活跃的学期的课程,只有学期不是 .

这有什么不对吗?或者还有其他方式吗?

2 回答

  • 1

    现在我有了一个解决方案:我使用了 joins 选项来查找方法 .

    "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
    ),
    
  • 0

    当您使用contains时,就像您的情况一样,查询不是直接内连接,即Class内连接与Semester . 首先拉出类记录,然后在学期表上会有第二个查询条件(其中class_id IN(第一个查询的结果) . 所以即使在学期表中没有找到记录,蛋糕仍然会返回找到 class 记录 .

    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个结果 .

相关问题