php - How to model a many to many relationship? -
Only a bit of past experience with the database and no formal education with them, how can I model this Retrieve the data needed for it) This is what I'm trying to model:
For each item on my site, allow it to upload multiple tags such as files, uploads, PHP, recursive, etc. is. Although the tags are reusable, I can do two different items and each of them can have a php tag.
How have I read it and whether it is lacking in experience or I do not know, but I am unable to understand this concept. Obviously you need a central table that connects both together?
Once I have a definition of these relationships and tables, how will I work like this: - Recover all items with a certain tag? - Retrieve all tags of an item?
Thank you for your help, if anyone can list it to strengthen my understanding of the concept to read more on this.
DB part is easy. It's just a sample so that you can see how a particular SQL Engine can look like a database, not just queries. Create table post (ID INT primary key, topic VARCHAR (100), body text) Table tag (ID INT primary key, name VARCHAR (50)) CREATE TABLE post_tags (post_id INT) , Tag_id INT, foreign key (post_id) posts (id), foreign key (tag_id reference) reference posts (id))
yourTag
tags To get the item with the curiosity run, select
from the P * post to the left post_tags on PT (PT.post_id = P.id) LEFT JOIN tag T ON (T. Id = PT.tag_id) WHERE T.name = 'yo UrTag '; You run this query to get the tag tag with the post with 123
ID:
SELECT T. * F LEFT JOIN POST_TAG PT ON (TID = PT. TAG_ID) to the left zone post p on (pt.post_id = piid) where pad = 123;
For PHP part you can use a framework. Many (if not all) frameworks can easily model such relationships, for example, this is done in KPHP:
AppModel extends into the class post {$ useTable = 'Posts'; $ HasAndBelongsToMany = array ('Tag' = & gt; array ('className' => gt; 'tag' joinTable '=' gt; 'post_tags' foreignKey '= & gt;' POST_ID 'associationforeignKey' = & gt; ; 'Tag_id')); } Class tag extends AppModel {$ useTable = 'tags'; $ HasAndBelongsToMany = array ('post' = & gt; array ('className' = & gt; 'post' 'joinTable' = & gt; '' post_tags 'foreignKey' = & gt; 'tag_id' 'associationforeignKey' = & gt; ; 'POST_ID')); }
Comments
Post a Comment