CakePHP Two Relationships Between Models - mysql

I have the following tables: 'assets', 'pictures', 'assets_pictures', 'othermodels', 'othermodels_pictures', etc...
From the above you probably already figured that table 'pictures' serves as a repository of images and is related to multiple models, including 'assets'.
I want model 'Asset' (table 'assets'), to have:
hasMany relationship with 'Picture' (using table 'assets_pictures')
hasOne relationship with 'Cover' (table 'pictures'), based on a 'cover_id' field in 'assets' associated with 'Picture.id'
So far it seems to work when I setup HABTM relationship between Asset and Picture, and 'Asset' belongsTo 'Cover'. Somehow this doesn't sound right, moreover changing the cover picture of an asset wipes out all HABTM relationships in 'assets_pictures' for that asset, so I know something's wrong here. I'm at loss...

It doesn't sound right because you are setting up multiple relationships between two tables at the database level. Not sure which ones, but this definitely breaks a few database normalization rules.
Imagine that later on you decide that you want to be able to track not only the cover, but also the back. You would have to add another field to the asset table called back_id, which would point back to pictures. A real mess...
The proper way to represent this is to include a 'type' field in the assets_pictures table:
You can default this field to "normal" (or even null), and change it to "cover" when needed. Note that this field allows for additional picture types (e.g. "back").
HABTM relationships can handle this without too many problems. The parameter 'unique'=>'keepExisting' prevents CakePHP from dropping other relationships already in place (which is the default behavior).
However, things can get complicated with 'rich' HABTM relationships, particularly when trying to save data. If this happens, and before you pull out your hair, you may want to go down the 'hasMany through' route.
For convenience, and to retrieve information, you may want to set up an additional HABTM relationship for Cover in model Asset, which would look something like this:
public $hasAndBelongsToMany = array(
'Cover' => array(
'className' => 'Picture',
'conditions' => array('AssetCover.type' => 'cover'),
)

Related

Laravel User Model with two relationships to same Model

I have a User model and an Events model. A User has_many Events (can create several events), and Events belong to User. However, since my Events also have a registration, I thought the best way would be to add a pivot table users_events_table that would contain all the registration, and now both Models pass to the belongs_to relationship.
Is there any way to maintain both relationships?
Yes - you're probably after a has many through relationship. It works similar to a belongs to many relationship except the pivot table is a first-class model, which means you can attach additional functionality to it. A user can have many events through registrations and vice-versa.
If you don't actually need that much additional information on the pivot table - maybe you just need created_at/updated_at timestamps then you can get away with belongs to many and pop withTimestamps() on the end - Laravel will handle that for you. It does allow you to add more columns on that pivot table but they can get tricky to manage depending on you use case, which is where has many through might become a better solution.

tags from multiple tables

From what I understand relational databases are ill-equipped to handle polymorphic relationships, but is there any easy way of integrating multiple tables into one tags table. Basically what I want to achieve is to have one tags table, but have the tag names derived from 1 of 3 table (games, platforms or companies). See the below design as a mock-up:
Am I looking at this from the wrong way or am I on the right track? Is there a different approach someone would suggest?
Your case sounds like a mismatch between relational modeling and object modeling. If you are interested in designing relational tables that provide the closest thing to inheritance (not polymorphism) then look up the questions, answers, and info under these tags:
single-table-inheritance class-table-inheritance
If you're interested in more detail, look up Martin Fowler's handling of the same techniques.
If your interest is in diagramming the IS-A relationship between games, platforms, or companies and some unnamed superclass that I'll call "Tag Providers" , then look up "EER generalization/specialization". (EER stands for Enhanced Entity Relationship). This shows how to diagram the relationship, without providing any details about how to implement it.
You are correct as there is Many to many relationship between article,video & tags.
See,
One article => with => Many tags
One tag => belongs to => Many articles .
So to preserve mapping 3rd,4th mapping table is necessary .
3rd Table will have relationship between Article+Tags
4th Table will have relationship between Video+Tags
Update =>
For other tables to relate with Tags table , Make 3 more tables :
5th Table will have relationship between Company+Tags => companies_tags
6th Table will have relationship between Game+Tags => games_tags
7th Table will have relationship between Platform+Tags => platforms_tags

Need suggestion on DB architecture

I am working on a Project where I have below use case.
User can have many taglines for them , we have lot of predefined data in the DB which we using to show autosuggestion when they started typing tag lines, I am using Rails.
User has_and_belongs_to_many taglines
Tagline has_and_belongs_to_many users
I have separate joint table and everything was fine , but now I need to store custom taglines of user to DB , which will be belongs to only particular user.
Should I clone the taglines table and add user ID to it Or what is the best architecture to handle these kind of scenario , if we have more than one model which have same use case as like taglines.
your existing user and tagline table has many-to-many relationship, keep it that way. Whereas the user table and the new customTagline has a one-to-many relationship so why don't you create a new table to represent it? Since you mentioned the customTagline belongs to only a particular user.
#BroiSatse Comment make sense, I followed same.
If you create a second table, you will need to remember to update two
tables/models every time you will want to change your model. You won;t
be able to pull all the user tags in one go neither. many-to-many is
able to hold one-to-many association. Just add a validation to check
that given tag can belong to only one user if it is custom.

Database Design - structure

I'm designing a website with courses and jobs.
I have a jobs table and courses table, and each job or course is offered by a 'body', which is either an institution(offering courses) or a company(offering jobs). I am deciding between these two options:
option1: use a 'Bodies' table, with a body_type column for both insitutions and companies.
option2: use separate 'institution' and 'company' tables.
My main problem is that there is also a post table where all adverts for courses and jobs are displayed from. Therefore if I go with the first option, I would just need to put a body_id as a record for each post, whereas if I choose the second option, I would need to have an extra join somewhere when displaying posts.
Which option is best? or is there an alternative design?
Don't think so much in terms of SQL syntax and "extra joins", think more in terms of models, entities, attributes, and relations.
At the highest level, your model's central entity is a Post. What are the attributes of a post?
Who posted it
When it was posted
Its contents
Some additional metadata for search purposes
(Others?)
Each of these attributes is either unique to that post and therefore should be in the post table directly, or is not and should be in a table which is related; one obvious example is "who posted it" - this should simply be a PostedBy field with an ID which relates another table for poster/body entities. (NB: Your poster entity does not necessarily have to be your body entity ...)
Your poster/body entity has its own attributes that are either unique to each poster/body, or again, should be in some normalized entity of their own.
Are job posts and course posts substantially different? Perhaps you should consider CoursePosts and JobPosts subset tables with job- and course-specific data, and then join these to your Posts table.
The key thing is to get your model in such a state that all of the entity attributes and relationships make sense where they are. Correctly modeling your actual entities will prevent both performance and logic issues down the line.
For your specific question, if your bodies are generally identical in terms of attributes (name, contact info, etc) then you want to put them in the same table. If they are substantially different, then they should probably be in different tables. And if they are substantially different, and your jobs and courses are substantially different, then definitely consider creating two entirely different data models for JobPosts versus CoursePosts and then simply linking them in some superset table of Posts. But as you can tell, from an object-oriented perspective, if your Posts have nothing in common but perhaps a unique key identifier and some administrative metadata, you might even ask why you're mixing these two entities in your application.
When resolving hierarchies there are usually 3 options:
Kill children: Your option 1
Kill parent: Your option 2
Keep both
I get the issue you're talking about when you kill the parent. Basically, you don't know to what table you have to create a foreign key. So unless you also create a post hierarchy where you have a post related to institution and a separate post table relating to company (horrible solution!) that is a no go. You could also solve this outside the design itself adding metadata in each post stating which table they should join against (not a good option either as your schema will not be self documentation and the data will determine how to join tables... which is error prone).
So I would discard killing the parent. Killing the children works good if you don't have too many different fields between the different tables. Also you should bear in mind that that approach is not good to solve issues wether the children can be both: institution and companies but it doesn't seem to be the case. Killing the children is also the most efficient one.
The third option that you haven't evaluated is the keeping both approach. This way you keep a dummy table containing the shared values between the bodies and each of the bodies have a FK to this "abstract" table (if you know what I mean). This is usually the least efficient way but most likely the most flexible. This way you can easily handle bodies that are of both types, and also that are only of type "body" but not a company nor an institution themselves (if that is even possible or might be possible in the future). You should note that in order to join a post to an institution you should always reference the parent table and then join the parent with the children.
This question might also be useful for you:
What is the best database schema to support values that are only appropriate to specific rows?

How to create mysql table with many hasMany association in CakePHP?

I'm defining a completely new database. I have now faced a problem
which I would describe as "usual" but still could not find good
information from web. So here's the problem:
I have many tables in my database (which I would describe as guides) such as:
Skills
Places
Activities
and so on...
Now to all these guide types I'd like to add a comment feature and
other similar features like attaching images and videos. I have many guide types so I dropped the idea of having a separate comment image and video tables for each of them. I need one table for each of them.
The question is, what is the best way to achieve this? I have heard and read about 3 solutions and I'm not familiar with none of them.
I have read about using UUIDs would fix this problem but I'm not very familiar how they function. Could someone elaborate on that if that is the correct way to go? Something about UUIDs I read but not quite understood it.
Other thing I have read about is creating a hierarchial model "tree table" which would hold association links. More info at Managing Hierarchical Data in MySQL.
I have also read about creating object tables and using program like object inheritance inside MySQL in a similar way like the hierarchical model.
UUIDs sound most simple so I would appreciate help in there.
I don't know anything about how to use them. But here's how I thought it works - at least you'll get a hang of it what I'm trying to achieve here and how/what I'm misunderstanding about them:
I would create a new table: Guides which could have UUID field.
Then link all those guide types (Skills etc.) to guide table (Guide as parent and the other as child)
Parent and Child have both UUID fields and when creating a guide Parent and Child gets same UUID so they can be linked. Child also has its own Id field.
Then link comments to Guides by using UUID field that points to Guide plus separate id int field for comments.
Please tell me if this is correct way or is it total garbage and if so, how I should do it?
Have you though about using a normal hasMany relationship with a condition? Read about it here.
class Skill extends AppModel {
var $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'conditions' => array('Comment.type' => 1), // 1 for skills, 2 for places etc. or something like that.
)
);
}
Check http://cakeapp.com, create your DB layout there and download the SQL later.
I read more about UUIDs and since they allow application wide unique IDs I was able to do "inheritance" style of database.
I used my own prefix at the start of the every table name to avoid reserved table name collisions such as object. You can use any kind of prefix, for example: my_ and to use it like: my_object. All tables should use prefixes in this example.
So I created table Objects. It has the id field with Binary(36) type. Cake recognizes it as UUID field. Then I used 1:1 identifying relationships and inherited other tables from it, which I wanted to interact with others.
So I created 1:1 identifying relationship to Comments, Videos, Pictures table so that the table had the identifying foreign key being also a primary key.
Then I created Mappings table to which I used two 1:1 non-identifying relationships without primary key. This means this was really HABTM relationship to self.
Now this let me to "inherit" other tables from Objects table, like News table with again 1:1 identifying relationship. Then it was possible to link Comments, or anything other that has the 1:1 identifying relationship to Object, to News table by using the Mappings table.
I hope this will help others who are pondering this kind of solution aswell.