【问题标题】:CakePHP conditions in associated Models关联模型中的 CakePHP 条件
【发布时间】:2013-12-02 06:45:26
【问题描述】:

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

UserhasAndBelongsToMany Class(通过访问 Class属于Semester

现在我想在活动的Semester 中查看所有VisitsClassesSemester 表有一个字段is_active) 我读到了 find 方法的包含选项,并尝试了这样的方法:

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

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

这有什么问题吗?还是有别的办法?

【问题讨论】:

  • 所以:Visits 属于ClassClass 属于Semester,对吗?

标签: cakephp model conditional-statements database-relations contain


【解决方案1】:

现在我有一个解决方案: 我为 find 方法使用了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
),

【讨论】:

    【解决方案2】:

    当您使用包含时,就像您的情况一样,查询不是直接内连接,即类内连接与学期。 首先提取课程记录,然后在学期表上进行第二次查询,条件为(其中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 个结果。

    【讨论】:

    • 您可以通过学期模型进行查询...这样,您首先提取活动学期,然后将课程加入结果中,从而消除不需要的课程
    猜你喜欢
    • 2023-03-16
    • 1970-01-01
    • 2012-01-05
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多