Clever category conditioning

#1

In my project User is linked with some of the Markets. User is allowed only to select data from those Market.

First - I’ve linked user and Market with many-to-many relations in their respective model definition and created a proxy model (UserMarket).

User -> hasMany('UserMarket');
Market -> hasMany('UserMarket');

To make selection simple, I’ve created a market model, which would list available market for currently-loggedin user:

class Market_Available extends Market {
    function init(){
        parent::init();
        $um=$this->join('user_market.market_id');
        $um->addField('user_id');
        $this->addCondition('user_id', $this->app->auth->model->id);
    }
}

I tested this model inside lister and it appears to show only the markets available for the currently logged-in user. My next step is to show some market data to the user .

MarketData -> hasOne('Market');

I thought what would be the great way to limit the Market Data to only show data for markets user is allowed to see. One option is to get all data from Market_Available and add into condition, but that would result in an extra query. Here is a solution, how to add this condition without any extra Queries:

class MarketData_Available extends MarketData {
    function init() {
        parent::init();
        $this->addCondition('market_id', $this->add('Model_Market_Available')->fieldQuery('id'));
    }
}

The above code produces a sub-query for the “id” field based on the market condition for a current user and specifies it as a sub-select inside MarketData_Available.

1 Like
#2

Nice! I always wondered how to do this kind of thing. Thanks for the info Romans :slight_smile: