具有相关条件的CakePHP模型 [英] CakePHP Models with associated conditions

查看:88
本文介绍了具有相关条件的CakePHP模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个型号如下:

位置hasMany SportType有多个运动,然后
运动属于SportType属于位置

Location hasMany SportType hasMany Sport, then Sport belongsTo SportType belongsTo Location

在SportType模型中,belongsTo Location的条件为Location.status=> true,因此它只检索Location状态为true的记录。工作正常。

In the SportType model, the belongsTo Location has a condition 'Location.status' => true, such that it only retrieves records where the Location status is true. Works fine.

当在运动模型中通过一个普通的find()检索记录时,我假设它不会返回关联的SportType的相关位置为false的记录,但是不是这样。

When retrieving records via a plain old find() in the Sport model, I would assume that it would not return records where the associated SportType's associated Location was false, but that is not the case.

我相信我可以使用可控行为或明确构造的连接在我的控制器,以获得我想要的,但我想知道如果这是我可以通过模型关系实现的东西。也许不是。

I believe I could use containable behavior or explicitly constructed joins in my controller to get what I want, but I'm wondering if this is something I can achieve purely through the model relationships. Perhaps not.

推荐答案

您可以使用 Joins 你正在通过限制模型(即 Location )进行搜索。

You can either use Joins or change the model you're doing the search on and do it through the restricting model (ie Location).

$this->Location->find('all', array(
    'conditions' => array(
        'Location.status' => true
    ),
    'contain' => array(
        'SportType' => array(
            'Sport'
        )
    )
));

但是,您无法根据包含模型中的条件缩小搜索模型的结果。

But you cannot narrow the results of the searching model based on conditions within contained models.

更新:

加入还允许您向其他模型添加更多条件... ,而不是包含它不,所以我想我会倾向于与联合会,因为这给你更多的灵活性向前迈进。

Joins also allow you to add more conditions to other models...etc, as opposed to Contain which does not, so I supposed I'd lean toward going with Joins as that leaves you more flexibility moving forward.

此外,JOIN会做一个更复杂的查询,而一个包含将做许多更简单的查询...所以取决于你的数据库结构,可以考虑。

Also, a JOIN will do one more-complicated query, while a contain will do many simpler queries... so depending on your database structure, that could be considered.

底线,两者都很好,对你适用的是伟大的。

Bottom line, it's preference - both are just fine and whichever works for you is great.

这篇关于具有相关条件的CakePHP模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆