How Do I Set Up Relations With 2 Primary Keys

Hi

I’ve been searching for awhile but not sure which way is the best to set up relations between tables who has two primary keys.

I’ve designed the app so it allows multiple companies within the same database. Each company has its own set of data. I.e each company its set of country and zip codes.

4045

tables.JPG

I have the following tables (also see the image)

SysCompany - Holds all companies

AddressCountry - Holds all the countries for that company. PK => CountryId & CompanyId

AddressZipCode - Holds all the zip codes for that company. PK => ZipCodeId & CompanyId, FK => CountryId

Any suggestions to the best way to build the relations?

Its important that the users are only able to read the data within their own company.

Hope someone can point me in the right direction :)

Hi your relationships appears to be okay one thing to note there is only one primary key per table for instance

comanyId in address table is called foreign key.

I’ve been able to define the relations.

However I’ve come up with another issue…

My model/table has composite primary key (CountryId and CompanyId).

I’ve declared a default scope which ensures I only get teh countries for a given company and it works on the index action.

public function defaultScope()

{

return array(‘condition’ => “CompanyId=” . Yii::app()->user->getState(‘cmpId’));

}

But if I try to view a specific country I get some errors. It seems yii for some reason is demanding the two primary keys in my url. But I only want to give the CountryId in the url and let the scope handle the second primary key.

First I got some 400 - your request is invalid. I fixed this by changing the action to:

public function actionView(array $id)

{

$this->render(‘view’,array(‘model’=>$this->loadModel($id),));

}

So now it works if both primary keys are included.

But, how can i make it work with only one primary key included?

I’ve tried to implement the following code in the model with no luck

public function actionView(array $id)

{

$this->render(‘view’,array(‘model’=>$this->loadModel($id),));

}

public function actionView(array $id)

{

$this->render(‘view’,array(‘model’=>$this->loadModel($id),));

}

Any clues on what I should do?

Change loadModel in my controller

public function loadModel($id)

{

$model = AddressCountry::model()->findByPk(array($id[‘CountryId’], Yii::app()->user->getState(‘cmpId’, 0)));

Which only result in the following error message

The value for the column "CountryId" is not supplied when querying the table "AddressCountry".