many-to-many interview questions
Top many-to-many frequently asked interview questions
There is a handy dynamic attribute in active-record called find_or_create_by:
Model.find_or_create_by_<attribute>(:<attribute> => "")
But what if I need to find_or_create by more than one attribute?
Say I have a model to handle a M:M relationship between Group and Member called GroupMember. I could have many instances where member_id = 4, but I don't ever want more than once instance where member_id = 4 and group_id = 7. I'm trying to figure out if it's possible to do something like this:
GroupMember.find_or_create(:member_id => 4, :group_id => 7)
I realize there may be better ways to handle this, but I like the convenience of the idea of find_or_create.
Source: (StackOverflow)
Here is the case,I have 2 entities,such as Contract、Media。
public class Media : Entity
{
public string Name {get; set;}
public bool Enabled
*//other properties can be ignored..*
}
public class Contract : Entity
{
public string Code {get; set;}
*//other properties can be ignored..*
}
Contract has many Medias, it seems that they are many to many.
But!! at ef code first, i need 3 more fields in the ContractMedia table(ef auto generated).
such as StartDate,EndDate and Price. these could not be added in Media entity.
How to map at this case??
hope you understand it,my english is so so :-)
Source: (StackOverflow)
I am trying to print a list of all the Conferences and for each conference, print its 3 Speakers.
In my template I have:
{% if conferences %}
<ul>
{% for conference in conferences %}
<li>{{ conference.date }}</li>
{% for speakers in conference.speakers %}
<li>{{ conference.speakers }}</li>
{% endfor %}
{% endfor %}
</ul>
{% else %}
<p>No Conferences</p>
{% endif %}
in my views.py file I have:
from django.shortcuts import render_to_response
from youthconf.conference.models import Conference
def manageconf(request):
conferences = Conference.objects.all().order_by('-date')[:5]
return render_to_response('conference/manageconf.html', {'conferences': conferences})
there is a model named conference. which has a class named Conferences with a ManyToManyField named speakers
I get the error:
Caught an exception while rendering: 'ManyRelatedManager' object is not iterable
with this line: {% for speakers in conference.speakers %}
Source: (StackOverflow)
I have two PHP model classes named Category and Item. A Category may have many Items and an Item may belong to many Categories.
I have created a ManyToMany relation to both classes:
class Category
{
/**
* @ORM\ManyToMany(targetEntity="Item", mappedBy="categories", cascade={"persist"})
*/
private $items;
/**
* Add items
*
* @param Ako\StoreBundle\Entity\Item $items
*/
public function addItems(\Ako\StoreBundle\Entity\Item $items)
{
$this->items[] = $items;
}
/**
* Get items
*
* @return Doctrine\Common\Collections\Collection
*/
public function getItems()
{
return $this->items;
}
}
And:
class Item
{
/**
* @ORM\ManyToMany(targetEntity="Category", inversedBy="items", cascade={"persist"})
* @ORM\JoinTable(name="item_category",
* joinColumns={@ORM\JoinColumn(name="item_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="category_id", referencedColumnName="id")}
* )
*/
private $categories;
/**
* Add categories
*
* @param Ako\StoreBundle\Entity\Category $categories
*/
public function addCategories(\Ako\StoreBundle\Entity\Category $categories)
{
$this->categories[] = $categories;
}
/**
* Get categories
*
* @return Doctrine\Common\Collections\Collection
*/
public function getCategories()
{
return $this->categories;
}
}
Now in my controller:
$em = $this->getDoctrine()->getEntityManager();
$item = $em->getRepository('AkoStoreBundle:Item')->find($item_id);
$category = $em->getRepository('AkoStoreBundle:Category')->find($category_id);
$category->addItems($item);
$em->flush();
// Render the same page again.
In this page, I show the list of all items in a select field. The user can select one item, and add it to the category.
The list of items which belong to the category are shown below the form.
When the I submit the form, the selected item is added to the list of Category items, and is shown below, but it is not stored in the database, and if refresh the page, it disappears.
Can anyone please help me with this?
Thanks in advance.
Source: (StackOverflow)
Why do Java method names use the "get" prefix so extensively? At least in my Java programs there are a lot of methods with names starting with the word "get". The percentage of get-methods is suspiciously high. I am starting to feel that the word "get" is losing its meaning because of inflation. It is noise in my code.
I have noticed that there is a different naming convention being used in functional/declarative programming and PL/SQL. The method name simply states what the method returns. Instead of account.getAmount()
or Time.getIsoFormattedDateString(Date date)
they will use account.amount()
and Time.isoFormattedDateString(Date date)
. This makes perfect sense to me, as the name of the function describes the result of evaluating the method (assuming there are no side effects, which there shouldn't be anyway). The "get" prefix seems superfluous.
I have just started reading the book "Clean Code". It says that methods should do only one thing, and that that thing should normally be one of the following:
- Notify some object about an event, typically passing the event as a parameter.
- Ask a question about some object, typically with the method name forming a natural language statement, passing the object as parameter and returning a boolean.
- Fetch something, possibly passing some lookup key or some object to be converted as parameter and always returning the desired object/value.
My question is about the third category. Are there naming conventions other than "get" for this kind of methods? What criteria do you use when choosing method names/prefixes?
Here is an example:
I have a class with two methods getDates()
and getSpecialDates()
. getDates()
simply returns the value of a private variable (the reference to a collection of dates). This is a standard getter, as I understand it. getSpecialDates()
is different; it calls getDates()
, fetches a filter from another class, applies the filter and returns what is effectively a subset of getDates()
.
The method getSpecialDates() could be named computeSpecialDates()
, findSpecialDates()
, selectSpecialDates()
or elicitSpecialDates()
or whatever. Or I could simply name it specialDates()
. And then, for consistency, I could rename getDates()
into dates()
.
Why bother separating between methods that should be prefixed with "get" and methods that should not, and why bother finding replacement words for "get"?
Source: (StackOverflow)
I am using JPA 2.0 and hibernate. I have a User class and a Group class as follows:
public class User implements Serializable
{
@Id
@Column(name="USER_ID")
private String userId;
@ManyToMany
@JoinTable(name = "USER_GROUP",
joinColumns =
{
@JoinColumn(name = "GROUP_ID")
},
inverseJoinColumns =
{
@JoinColumn(name = "USER_ID")
})
private Set<Group> groupList;
//get set methods
}
public class Group
{
@Id
@Column(name="GROUP_ID")
private String groupId;
@ManyToMany(mappedBy="groupList")
private Set<User> memberList;
//get set methods
}
And then, I create a user and group and then assign the user to the group.
What I want to have is when I delete the group, the group will be deleted (of course) and all the user-group relationship that the group has will be automatically deleted from the USER_GROUP join table but the user itself is not deleted from the USER table.
With the code I have above, only the row in the GROUP table will be deleted when I delete a group and the user will still have an entry to the deleted group in the USER_GROUP join table.
If I put cascade in the User class like this:
@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(name = "USER_GROUP",
joinColumns =
{
@JoinColumn(name = "GROUP_ID")
},
inverseJoinColumns =
{
@JoinColumn(name = "USER_ID")
})
private Set<Group> groupList;
When I delete the group, the user will be deleted as well!
Is there any way to achieve what I want?
Source: (StackOverflow)
I have two tables/collections; Users and Groups. A user can be a member of any number of groups and a user can also be an owner of any number of groups. In a relational database I'd probably have a third table called UserGroups with a UserID column, a GroupID column and an IsOwner column.
I'm using MongoDB and I'm sure there is a different approach for this kind of relationship in a document database. Should I embed the list of groups and groups-as-owner inside the Users table as two arrays of ObjectIDs? Should I also store the list of members and owners in the Groups table as two arrays, effectively mirroring the relationship causing a duplication of relationship information?
Or is a bridging UserGroups table a legitimate concept in document databases for many to many relationships?
Thanks
Source: (StackOverflow)
From examples that I have seen online and in a Programming Entity Framework CodeFirst book, when you have a collection on both classes EF would create a mapping table such as MembersRecipes
and the primary key from each class would link to this table.
However when I do the below, I instead get a new field in the Recipes
table called Member_Id
and a Recipe_Id
in the Members
table.
Which only creates two one-to-many relationships, but not a many-to-many so I could have Member 3 linked to Recipes (4,5,6) and Recipe 4 linked to Members (1,2,3) etc.
Is there a way to create this mapping table? and if so how do you name it something else such as "cookbooks" ?
Thanks
public abstract class Entity {
[Required]
public int Id { get; set; }
}
public class Member : Entity {
[Required]
public string Name { get; set; }
public virtual IList<Recipe> Recipes { get; set; }
}
public class Recipe : Entity {
[Required]
public string Name { get; set; }
[ForeignKey("Author")]
public int AuthorId { get; set; }
public virtual Member Author { get; set; }
....
public virtual IList<Member> Members { get; set; }
}
UPDATE:
Below is another approach I have tried which doesn't use the Fluent API and replaces the AuthorId
& Author
on Recipe
with an owner flag, I have also renamed the below example from Cookbooks
to MembersRecipes
, this also fixes my issue similar to the answer but as mentioned has further implications.
public class MembersRecipes {
[Key, Column(Order = 0)]
[ForeignKey("Recipe")]
public int RecipeId { get; set; }
public virtual Recipe Recipe { get; set; }
[Key, Column(Order = 1)]
[ForeignKey("Member")]
public int MemberId { get; set; }
public virtual Member Member { get; set; }
public bool Owner { get; set; }
}
and in Recipe
& Member
classes I changed the collections to
public virtual IList<MembersRecipes> MembersRecipes { get; set; }
Source: (StackOverflow)
Ok so this is probably a trivial question but I'm having trouble visualizing and understanding the differences and when to use each. I'm also a little unclear as to how concepts like uni-directional and bi-directional mappings affect the one-to-many/many-to-many relationships. I'm using Hibernate right now so any explanation that's ORM related will be helpful.
As an example let's say I have the following set-up:
public class Person{
private Long personId;
private Set<Skill> skills;
//Getters and setters
}
public class Skill{
private Long skillId;
private String skillName;
//Getters and setters
}
So in this case what kind of mapping would I have? Answers to this specific example are definitely appreciated but I would also really like an overview of when to use either one-to-many and many-to-many and when to use a join table versus a join column and unidirectional versus bidirectional.
Source: (StackOverflow)
When you have a many-to-many relationship (related_name
, not through
) and you are trying to use the admin interface you are required to enter one of the relationships even though it does not have to exist for you to create the first entry.
I'm creating an app that is an event organizer. Imagine we had Event
and Group
models, bound with many-to-many relationship.
Django related_name
creates another table with the indices of the two other tables.
But I see no reason why this extra table has to be populated.
If I work with the database through phpMyAdmin I can create a Group
without registering an Event
, since the connection between the two is only through a separate table, and there is no database value enforcement at given level.
How do I make the admin interface this realize it?
How do I make the many-to-many field optional in Django?
Source: (StackOverflow)
for item in data:
category_id = item['category_id']
del item['category_id']
category = Category.objects.get(pk=category_id)
code = item['code']
try:
article = Article.objects.get(pk=code)
except:
article = Article(**item)
article.save()
# at this point I have the article & category, but the next
# statement throws me an error:
category.articles.add(article)
category.save()
The error is:
AttributeError: 'ManyRelatedManager' object has no attribute 'add'
Source: (StackOverflow)
In Django, when you have a parent class and multiple child classes that inherit from it you would normally access a child through parentclass.childclass1_set or parentclass.childclass2_set, but what if I don't know the name of the specific child class I want?
Is there a way to get the related objects in the parent->child direction without knowing the child class name?
Source: (StackOverflow)
My database contains 3 tables:
User and Service entities have many-to-many relationship and are joined with the SERVICE_USER table as follows:
USERS - SERVICE_USER - SERVICES
SERVICE_USER table contains additional BLOCKED column.
What is the best way to perform such a mapping?
These are my Entity classes
@Entity
@Table(name = "USERS")
public class User implements java.io.Serializable {
private String userid;
private String email;
@Id
@Column(name = "USERID", unique = true, nullable = false,)
public String getUserid() {
return this.userid;
}
.... some get/set methods
}
@Entity
@Table(name = "SERVICES")
public class CmsService implements java.io.Serializable {
private String serviceCode;
@Id
@Column(name = "SERVICE_CODE", unique = true, nullable = false, length = 100)
public String getServiceCode() {
return this.serviceCode;
}
.... some additional fields and get/set methods
}
I followed this example http://giannigar.wordpress.com/2009/09/04/m ... using-jpa/
Here is some test code:
User user = new User();
user.setEmail("e2");
user.setUserid("ui2");
user.setPassword("p2");
CmsService service= new CmsService("cd2","name2");
List<UserService> userServiceList = new ArrayList<UserService>();
UserService userService = new UserService();
userService.setService(service);
userService.setUser(user);
userService.setBlocked(true);
service.getUserServices().add(userService);
userDAO.save(user);
The problem is that hibernate persists User object and UserService one. No success with the CmsService object
I tried to use EAGER fetch - no progress
Is it possible to achieve the behaviour I'm expecting with the mapping provided above?
Maybe there is some more elegant way of mapping many to many join table with additional column?
Source: (StackOverflow)
This question comes up after reading a comment in this question:
http://stackoverflow.com/questions/2190089/database-design/2190101
When you create a many-to-many table, should you create a composite primary key on the two foreign key columns, or create a auto-increment surrogate "ID" primary key, and just put indexes on your two FK columns (and maybe a unique constraint)? What are the implications on performance for inserting new records/re-indexing in each case?
Basically, this:
PartDevice
----------
PartID (PK/FK)
DeviceID (PK/FK)
vs. this:
PartDevice
----------
ID (PK/auto-increment)
PartID (FK)
DeviceID (FK)
The commenter says:
making the two IDs the PK means the
table is physically sorted on the disk
in that order. So if we insert
(Part1/Device1), (Part1/Device2),
(Part2/Device3), then (Part 1/Device3)
the database will have to break the
table apart and insert the last one
between entries 2 and 3. For many
records, this becomes very problematic
as it involves shuffling hundreds,
thousands, or millions of records
every time one is added. By contrast,
an autoincrementing PK allows the new
records to be tacked on to the end.
The reason I'm asking is because I've always been inclined to do the composite primary key with no surrogate auto-increment column, but I'm not sure if the surrogate key is actually more performant.
Source: (StackOverflow)
I have this scenario:
public class Member
{
public int MemberID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
public class Comment
{
public int CommentID { get; set; }
public string Message { get; set; }
public virtual ICollection<Member> Members { get; set; }
}
public class MemberComment
{
public int MemberID { get; set; }
public int CommentID { get; set; }
public int Something { get; set; }
public string SomethingElse { get; set; }
}
How do I configure my association with fluent API? Or is there a better way to create the association table?
Source: (StackOverflow)