Relation BELONGS_TO

Hi,

I have two tables: User (primary key: id) and History (primary key: table, tableId - primary key created by database).

Table History is used to store the history of company, user and member.

Ie.

Member:

id      login        password

1      member1  pass1

2      member2  pass2

User:

id      login        password

1      user1      pass1

2      user2      pass2

History:

table      tableId    task

user      1            LOGIN

user      2            LOGOUT

member  2          JOIN

user      2            LOGIN

My question is, how can I read all users (table user) who have task LOGIN?

I have following relations:

Table History:



public function relations()


{


	return array(


		'member'=>array(self::BELONGS_TO, 'Member', 'tableId'),	


		'user'=>array(self::BELONGS_TO, 'User', 'tableId'),	


	);


}


Table User:



public function relations()


{


	return array(


		'history'=>array(self::HAS_MANY, 'History', 'tableId','condition'=>'??.table="user"'),


	);


}


When I try:



$history=History::model()->with('user')->findAll('task="LOGIN"');





foreach($history as $model)


	echo $model->user->username;


I get error:

Quote

Trying to get property of non-object

Thanks for help!

Nobody knows what's wrong?

It means some of your history records do not refer to a user.

You might have to change your query like this:

$history=History::model()->with('user')->findAll('table="user" AND task="LOGIN"');

Since you do not really have a normal foreign key in the history table there could still be a history record for a user that does not exist anymore, so you should do this in your loop:



foreach($history as $model)


    echo ($model->user) ? CHtml::encode($model->user->username) : '';