Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii CActiveRecord: find related data, but not using the primary key

I have this code in my model for "Application", I'm trying to get all the related "Campaign" objects

public function relations()
{
    return array(
        'campaigns' => array(self::HAS_MANY, 'Campaign', 'appKey'),
    );
}

My problem is, the 'appKey' field in the campaigns table is not the primary key of the applications table and this is what Yii is using to try and find the campaigns.

The primary key of my applications table is 'id' but I would like it to use 'appKey'. How can I update my relations method to do this without making it the primary key?

Thanks.

like image 914
James Zaghini Avatar asked Jan 29 '26 05:01

James Zaghini


1 Answers

You could set up a named scope in the Campaign model, like so:

public function byApplication($appKey)
{
    $this->getDbCriteria()->mergeWith(array(
        'condition'=>'appKey = :appkey',
        'params'=>array('appKey'=>$appKey),
    ));
    return $this;
}

And call it like this:

$campaigns = Campaign::model()->byApplication($appKey);

Or, as Irobb said, just set up a query function in your Application model instead of using an actual Relation, like so:

public function getCampaigns() {
    return Campaign::model()->findallbyAttributes(array('appKey'=>$this->appKey));
}

And call it like a regular relation on your Application $model:

$campaigns = $model->campaigns; // remember with Yii you can call getters w/o the 'get'
like image 146
thaddeusmt Avatar answered Jan 31 '26 22:01

thaddeusmt