how to relation using not primary key

lets say we have two tables

  1. user with

type_id column

  1. userType with

id

type_id

type_name

how to write relation in User model ? where user.type_id = userType.type_id (not userType.id)

i am new, i am tired, google is not working for me this time, please help, thx

try in your model:


public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

                    'Type' => array(self::HAS_ONE, 'UserType', 'type_id',

                    );

	}

than use User::model()->with(‘Type’)->findAll();

hope this helps

hi! thank you for message, didn’t manage to make it work though :mellow: ,

second part of the story is that phpunit test is failing:

/* below 2 lines works */

$o = User::model()->findByAttributes(array(‘name’ => 'Bob));

$this->assertTrue($o instanceof User);

/* but this fails with Trying to get property of non-object */

print_r($o->Type->type_name);

in user_type table there are two indexes PRIMARY on id and second on type_id

in desperate try i have removed all of them and created PRIMARY on type_id and relation started to work…

is it how it schould be done, or is it a hack?

try $o = User::model()->with(‘Type’)->findByAttributes(array(‘name’ => ‘Bob’));

[not tested, so not sure if it will work]

still no joy :mellow:

general question then, can relation be defined on non PRIMARY index?

tableOne.columnX (many) = (one) tableTwo.columnY, where columnY is not PRIMARY index?

http://www.yiiframework.com/forum/index.php?/topic/4148-ar-relation-foreign-key/