[Solved] How to use database views in models?

Hi everyone,

i’m facing the following problem:

i have an AR where i used a standard db table till now. But now i need to use a database view as base table for this model.

The big problem is that yii (of course) can’t find a primary key in this view (because a view itself hasn’t any).

If i use this model in a relation it ends up with:

because it tries to execute the following command

...  LEFT OUTER JOIN `city` t1 ON (`employee`.`oid`=t1.``) ...

where ‘city’ is my view. But as you can see there is no PK found and therefore it’s an empty columnname in the query.

Is there a possibility to add the primary key name by hand, also when using the static model?

Thanks and best regards,


You can try this.


which ‘key_of_view’ is the column name you want to use as PK in your view.


thanks for your reply.

This was also my first idea, but i didn’t find the right place to add this.

Because i want to have this in my model and not in the code where i call it. And it should also been applied to static model calls…

Any suggestions on where to add this code?



It’s kind of urgent. No ideas?

What about overriding the init() method? Maybe a dumb question, did you try overriding the primaryKey() method in your AR class?

BTW, regarding "static method calls", did you mean calls like City::model()->someMethod() ? I just figured out by reading the source that, while model() is a static method, it returns a shared class instance, which is created on demand.


Oh my goodness!

Sometimes it’s that easy! I don’t know why but i’ve never seen the primaryKey method only the primaryKey property.

That’s exactly what i was looking for.

Thank you, tri!

Further on:

yes, i ment s.th. like City::model()->someMethod(). I didn’t dig into the instance generation. I’ve just overridden the init() method and set a trace which showed me that it’s not called when using such a method call.

Thank you!