0

我正在尝试创建一个将在 CActiveDataProvider 中使用的 CDbCriteria,我需要在多对多关系的另一侧查询一个值。

我有以下表格:order、user_order 和 user

正确声明了关系,因此我可以访问 $order->users[0] 并正确查看数据。

我正在尝试建立以下标准:

$criteria=new CDbCriteria;
$criteria->with  = array('users');
if (isset($_SESSION['hideCard'])){
    $criteria->condition = "fname != 'Card'";
}

return new CActiveDataProvider(get_class($this), array(
    'criteria'=>$criteria,
    'pagination'=>array('pageSize'=>40)
));

这基本上意味着如果设置了会话变量,我想从 DataProvider 中隐藏所有 fname 为“Card”的用户。

关于如何在多对多关系中实现这一点的任何想法?

4

4 回答 4

1

You must modify your code like this:

$criteria=new CDbCriteria;
$criteria->with  = array('users'); // or just string – 'users';
if (isset($_SESSION['hideCard'])){
    $criteria->together = true; // critical fix
    $criteria->condition = "users.fname != 'Card'"; // table alias must be set to ensure filtering proper column
}
于 2013-10-13T16:28:32.043 回答
0

您应该能够使用:

if (isset($_SESSION['hideCard'])){
    $criteria->condition = "users.fname != 'Card'";
}

或者无论用户表的别名是什么,我只是假设它users来自关系名称。

于 2012-09-10T08:14:07.213 回答
0

我对正在运行的查询进行了分析,并开始构建自己的查询。

Here is the code which made it work...

public function searchRecent()
    {
        $criteria=new CDbCriteria;
        $criteria->with  = array('users');
        $criteria->join = 'LEFT JOIN user_order uo ON t.id = uo.order_id LEFT JOIN user u ON u.id = uo.user_id';
        $criteria->order     = 't.id DESC';
        if (isset($_SESSION['hideCard'])){
            $criteria->join .= " LEFT JOIN loyalty_members lm ON lm.user_id = u.id";
            $criteria->addCondition("magnetic_id IS NULL");
        }
        if (isset($_SESSION['hidePango'])){
            $criteria->addCondition("u.password != 'PANGO'", "AND");
        }
        $criteria->group = "t.id";
        return new CActiveDataProvider(get_class($this), array(
            'criteria'=>$criteria,
            'pagination'=>array('pageSize'=>40)
        ));
    }
于 2012-09-11T06:48:04.587 回答
0

CActiveDataProvider can take a model instance instead of just its class name. This allows you to preset all of your criteria in your model. Then you can use 'named scopes' in your model. e.g.

$model = Order::model();

if (isset($_SESSION['someCond'])) {
    $model->someNamedScope();
}
if (isset($_SESSION['otherCond'])) {
    $model->otherNamedScope();
}

return new CActiveDataProvider($model, ...)
于 2012-09-13T07:33:57.150 回答