开发者

Yii: Best way to reference rows in multiple tables?

What is the most Yii friendly 'standard' way to reference a record of any model?

I'm attempting to build a menu system where a user can create a menu item which links to another item on the site. Obviously a user would be able to link to a var开发者_运维技巧iety of types of content (models). I would to work this without using urls as the internal reference to give me greater flexibility.

So as mentioned in the comment bellow some sort of 'unified primary key'

I was thinking either every model is an extension of a base model and reference that, like in this question. Or to simply have a separate field for each model that can be referenced.

Maybe another way to do it would be to store the model and record id in a field and then just override active records relational 'magic'


What you are trying to do is a kind of a tough problem, because mySql only supports First Normal Form relationships and not OOP inheritance. This is called "polymorphic association". There are a couple solutions though. A really good SO answer which describes some of them can be found here:

Possible to do a MySQL foreign key to one of two possible tables?

One possible solution example (the second one listed in the link above, I think) with Yii might be to have a single "object" table with a "type" field, and then then separate tables with the fields needed for the other types of "objects". Then in the afterFind() method of the base Object model, look at the type field and attach type Behaviors to them that allow access to the type table columns.

Also, if you really just want an easier way to make links or short URLs, you could write some extra functions in the framework which basically just make linking to the object easier. Have separate models for all of the object types just like normal, but have a central table with a master Primary Key (or URL slug) which makes a relation to the individual types. You could override createUrl() so it just takes in the master key (regardless of content type) and then build the correct link by looking up what model/controller to use in the master table.

This is sort of what Drupal's URL aliases allow you to do. Easier than recreating a Drupal CCK like system! Which would be unnecessary anyway unless you really needed the flexibility to change the content in the future.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜