Retrieve pk based on other column value

DB tables

person (id, name, user_id) <-- fk to user table.

user (id, name)

comment (id, comment, project_id, person_id) <–fk to person table.

on login, id (from user) sets Yii::app()->user->id

User can comment on a project.

What i want to do, in pseudo code:

On save comment,

get person.id where person.user_id = Yii::app()user->id

set comment.person_id = person.id

Want to do this in the model and call when needed.

Don’t overthink it!





... //controller code dealing with $_POST stuff


if($model->validate()) //comment model presumably

  $user=User::model()->findByPk(Yii::app()->user->id);

  $model->person_id=$user->person->id //assuming 'person' relations and HAS_ONE relationship. Better try/catch exceptions here though.

  ... //do other stuff



Ended up creating this since i could not make the solution above work

public function beforeSave()


{


	if(&#036;this-&gt;isNewRecord)


	{


		&#036;this-&gt;user_created=Yii::app()-&gt;user-&gt;name;


		&#036;this-&gt;tenant_id = Yii::app()-&gt;user-&gt;tenantId;


		&#036;personId = Yii::app()-&gt;db-&gt;createCommand()


			-&gt;select('id')


			-&gt;from('person') 


			-&gt;where('user_id =' .Yii::App()-&gt;user-&gt;id)


			-&gt;queryScalar();


		&#036;this-&gt;person_id = &#036;personId;


	}


	else