如何从CakePHP中的关联模型中排除记录?

时间:2021-08-18 07:31:24

I'm creating a Q&A application in CakePHP, and I want to exclude my associations in some cases. Imagine the following:

我正在CakePHP中创建一个Q&A应用程序,我希望在某些情况下排除我的关联。想象一下:

I'm listing all questions on the first page using $this->Question->findAll();. Since I have the following association in my model:

我在第一页上列出所有问题,使用$ this-> Question-> findAll();.由于我的模型中有以下关联:

public $hasMany = array('Answer' =>
        array('className' => 'Answer',
            'order' => 'Answer.created DESC',
            'foreignKey' => 'post_id',
            'dependent' => true,
            'exclusive' => false,
        )
    );

All answers will get selected at the start page, which is not optimal. How could i do to exclude the answers in this particular method?

将在开始页面选择所有答案,这不是最佳选择。我怎么能排除这个特定方法的答案?

Thanks

2 个解决方案

#1


I quick look at the CakePHP API reveals that you've got an unbindModel method on the Model. So in you example you can do this:

我快速查看CakePHP API,发现你在Model上有一个unbindModel方法。所以在你的例子中你可以这样做:

$this->Question->unBindModel(array('hasMany' => array(’Answer’)))

Alternatively, you can use the Containable behaviour to only select the pieces from MySQL that you require for the current page view.

或者,您可以使用Containable行为仅选择当前页面视图所需的MySQL部分。

#2


If you are using CakePHP 1.2 you should think about Containable Behaviour. See http://cakebaker.42dh.com/2008/05/18/new-core-behavior-containable/ for details

如果您正在使用CakePHP 1.2,您应该考虑可包含行为。有关详细信息,请参见http://cakebaker.42dh.com/2008/05/18/new-core-behavior-containable/

#1


I quick look at the CakePHP API reveals that you've got an unbindModel method on the Model. So in you example you can do this:

我快速查看CakePHP API,发现你在Model上有一个unbindModel方法。所以在你的例子中你可以这样做:

$this->Question->unBindModel(array('hasMany' => array(’Answer’)))

Alternatively, you can use the Containable behaviour to only select the pieces from MySQL that you require for the current page view.

或者,您可以使用Containable行为仅选择当前页面视图所需的MySQL部分。

#2


If you are using CakePHP 1.2 you should think about Containable Behaviour. See http://cakebaker.42dh.com/2008/05/18/new-core-behavior-containable/ for details

如果您正在使用CakePHP 1.2,您应该考虑可包含行为。有关详细信息,请参见http://cakebaker.42dh.com/2008/05/18/new-core-behavior-containable/