FAQ Database Discussion Community


Ordering the results from a junction table based on values of the row its foreign key belongs to

mysql,many-to-many
I have three tables for a many-to-many: Authors, Authorships, Books. I would like to select rows from authorship and order it alphabetically according to the author this row belongs to. Example: -- Authors -- ID Name 1 Peter 2 Gregory 3 Daniel -- Authorships-- ID AuthorId BookId 1 1 1...

In django1.7 , Can one many to many relationship have another many to many relation?

many-to-many,relationship,django-1.7
In Django 1.7 , Can one many to many relationship have another many to many relation ? class KeyValues(models.Model): value=models.IntegerField(max_length=1,blank=True) class Key(models.Model): position=models.IntegerField(max_length=1,default=0,blank=True) keyValues= key=models.ManyToManyField(KeyValues) class FileDetails(models.Model): fileId = models.CharField(max_length = 100,primary_key=True,db_index=True) key=models.ManyToManyField(Key) I wanted to do this type of relation , But I'm getting an error , ERRORS: cloud.Key:...

How to create default relationship for 2 MySQL tables with many-to-many relationships?

mysql,sql,database,many-to-many,relational-database
In MySQL, I have 2 tables, A and B, with many-to-many relationships. And I have a pivot table, A_B, for the relationships between table A and B. In table A, there are some rows that I want to link to *ALL* (including current and future) rows in table B. For...

What is the shorter verb for “establishing a many-to-many relationship”?

many-to-many,terminology,relationships,relational-algebra
When we establish a one-to-one or many-to-one relationship, we can call it mapping. For example, we map a spouse to his/her spouse or each child to its parent. But what would be the verb singifying an establishment of a many-to-many relationship, underlining that it is not a 1+ to 1...

cakePHP 3.0 one to many relation

mysql,cakephp,many-to-many,one-to-many,cakephp-3.0
I have a projects table and an images' table. A project has many images, so it's a one to many relationship between the two tables. In the images view I can retrieve the project name that is related to an image by using: <?= $image->has('project') ? $this->Html->link($image->project->project_title, ['controller' => 'Projects',...

Soft delete on many-to-many association EclipseLink

java,jpa,orm,many-to-many,eclipselink
I want to rewrite the call delete operation (on association table) on a many-to-many association sending by EclipseLink when we use only java code. Let me explain the goal. I have 3 tables, person, unit and an associative one : PerInUnit, so a person can be in multiple units and...

many-to-many query mysql

mysql,sql,many-to-many
I have 3 tables: users +-----+--------+ | id | name | +-----+--------+ | 1 | John | +-----+--------+ | 2 | Mike | +-----+--------+ files +-----+--------+ | id | file | +-----+--------+ | 22 | file1 | +-----+--------+ | 23 | file2 | +-----+--------+ and table relationship usersfiles +-------+--------+ |...

MySQL duplicates data in SELECT from multiple tables

php,mysql,database,many-to-many
I have 6 tables, according to following structure the query i am using SELECT campaigns.idCampaign, users.idUser AS idUser, users.identification AS userIdentification, users.name AS userName, campaign_users.commission AS userCommission, campaign_files.idFile AS idFile, campaign_files.name AS fileName, clients.identification AS clientIdentification, suppliers.identification AS supplierIdentification FROM campaigns LEFT JOIN campaign_users ON( campaigns.idCampaign = campaign_users.idCampaign) LEFT JOIN...

how to add other columns to the joinTable in a Many To Many relationship in hibernate JPA?

database,jpa,many-to-many
I have two entities User and File . a File can be shared with many users and a user can receive many files . So it's a Many To Many relationship between the two entities . in the User class : @ManyToMany @JoinTable(name = "receiver_shared", joinColumns = @JoinColumn(name = "user_id",...

Text search on many-to-many relationship

mysql,full-text-search,subquery,many-to-many
I have three tables: cars, colours, and cars_has_colours, the first two of which have a many-to-many relationship. I'd like to search cars, ideally using MATCH and AGAINST. This is very simple to achieve if I wanted to search cars.name. I'd like to search colours with MATCH and AGAINST, if possible....

HashSet in EF many to many

c#,entity-framework,many-to-many
I'm trying to implement many to many in EF Code-first. I have found this code : public class Student { public Student() { } public int StudentId { get; set; } [Required] public string StudentName { get; set; } public virtual ICollection<Course> Courses { get; set; } } public class...

Spring cascade field not updated

spring,hibernate,many-to-many
I have an object with the following attribute but when I try to save the object this field is not merging. How can I solve the issue ? @ManyToMany(targetEntity = User.class, mappedBy = "userSites", fetch = FetchType.LAZY, cascade = CascadeType.ALL) @NotAudited private List<IUser> localIt; userSites: @BatchSize(size = 20) @ManyToMany(cascade =...

LEFT JOIN across three tables (with junction table)

sql,database,postgresql,many-to-many,left-join
In Postgres, is there a way to perform a left join between tables linked by a junction table, with some filtering on the linked table? Say, I have two tables, humans and pets, and I want to perform a query where I have the human ID, and the pet name....

JPA and Hibernate persisting @manytoOne relationship

java,jpa,many-to-many,one-to-many,hibernate-cascade
I have this situation: @Entity @Table(name = "project_leader") public class ProjectLeader { @ManyToOne @JoinColumn(name = "projectId") @JsonBackReference(value = "project") private Project project; ... and related entity @Entity @Table(name = "project") public class Project { @OneToMany(fetch = FetchType.EAGER, mappedBy = "project", orphanRemoval = true) @Cascade(CascadeType.ALL) @JsonManagedReference(value = "project") private Set<ProjectLeader> projectLeaders...

How to list objects in many to many Django

django,many-to-many,django-queryset
Considerer this model class Dealership(models.Model): dealership = models.CharField(max_length=50) class Ordered(models.Model): customer = models.ForeignKey("Customer") dealership = models.ManyToManyField("Dealership") status = models.CharField(max_length=2, choices=status_list, default='p') I try $ ./manage.py shell >>> from new_way.core.models import Ordered, Dealership >>> q = Ordered.objects.all()[:5] >>> [i.dealership for i in q.dealership.all] And generate error Traceback (most recent call last):...

Entity framework fluent mapping many-to-may

c#,entity-framework,mapping,many-to-many,fluent
I'm having a problem when I try to map this model: public class Discipline { public int Id {get;set;} public string Name{get;set;} public virtual ICollection<DisciplineRequirement> Requirements {get;set;} } public class DisciplineRequirement { public int DisciplineId {get;set;} public int RequiredDiscipline {get;set;} public virtual Discipline Discipline {get;set;} public virtual Discipline RequiredDiscipline {get;set;}...

Symfony2: Deleting record in m:n-relationship

symfony2,many-to-many,crud
I have a problem, while deleting an entry in a m:n-table. I tried this solution, but I get the error: "ContextErrorException: Catchable Fatal Error: Argument 1 passed to Pso\ProjectBundle\Entity\Project::removeUser() must be an instance of Pso\LogBundle\Entity\User, string given, called in C:\xampp\htdocs\pso\src\Pso\ProjectBundle\Controller\ProjectController.php on line 59 and defined in C:\xampp\htdocs\pso\src\Pso\ProjectBundle\Entity\Project.php line 452" I...

Search a Many to Many Relationship

django,django-models,many-to-many,manytomanyfield
Given a Contributor, I'm trying to find the Registrations the Contributor belongs to. I can't figure out how to traverse the M2M- I need to know which Registrations contain the Contributor in their 'conrtibutor' field...? class Registration(TimeStampedModel): dataset = models.ForeignKey('Dataset', related_name='registration') contributor = models.ManyToManyField('Contributor', related_name='registrations') # many contributors may be...

Empty association table when trying to save many-to-many relationships between entities

c#,nhibernate,many-to-many,nhibernate-mapping
I have User entities (User mapping file) and Role entities (Role mapping file). I create some Users and Roles, assign roles to users and users to roles, save the whole lot, retrieve a User and test some assumptions (which fail). Here's my test code: [Test] public void TestUsersAndRolesWithoutWrappers() { //Ensure...

PHP results with MYSQL many to many table and GROUP By

php,mysql,many-to-many
I am putting together a list of service providers. I would like them to be listed like: Plumber: Joe's Plumbing Mike's Plumbing Electrician: Scott electric John electric etc... How can I pull and group this information from my query. Also when I try to call pt.name it says it is...

Doctrine, editing ManyToMany - Indirect modification of overloaded property

php,orm,doctrine,many-to-many
lets suppose I have something like this class Menu extends \Kdyby\Doctrine\Entities\BaseEntity { /** * @ORM\ManyToMany(targetEntity="MenuItem", mappedBy="menus") **/ protected $menuItems; function __construct() { $this->menuItems = new \Doctrine\Common\Collections\ArrayCollection(); } } and this class MenuItem extends \Kdyby\Doctrine\Entities\BaseEntity { /** * @ORM\ManyToMany(targetEntity="Menu", inversedBy="menuItems") * @ORM\JoinTable(name="cms_menuMenuItems") */ protected $menus; public function __construct() { $this->menus =...

HQL many to many between 3 tables

mysql,sql,hibernate,many-to-many,hql
I have 3 tables : User ->>- many to many ->>- Userapp ->>- many to many ->>- Application User have : userId userName UserApp : userId applicationId Applicaiton : applicationId applicaitonName I didn't succeed in creating a HQL query which returns every Application of one specific user. My HQL :...

Hibernate's ManyToMany simple use

java,spring,hibernate,jpa,many-to-many
I've two entities : CollabEntity and TechnoEntity. A collab can uses several technos. A techno can be used by several collabs. I would like to know all technos used by a specific collab. My DB looks like : CREATE TABLE collabs( co_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, co_firstname VARCHAR(25)...

django - Many To Many relationship issue

python,django,database,table,many-to-many
I am working in django, am planning a database for rides for users. each Ride can have multiple Users (passengers) on it, and multiple middle-destinations in it. also, each Destination can be in multiple Rides and each User (passenger) can be on multiple Rides (overtime). Also, for each Ride there...

@ManyToMany using @JoinTable

java,hibernate,many-to-many
i have the following two entities and one join table: entity: @Entity @Table(name = "PERSON") public class parent { @OneToOne(mappedBy="person", cascade= CascadeType.ALL) private Reader reader; //more fields and getters and setters and of course @Id..... } and another entity: @Entity @Table(name="READER") public class Reader{ @Id @Column(name= "READER_ID") @GeneratedValue(generator="gen") @GenericGenerator(name="gen", strategy="foreign",...

How can I do a count in Linq with many to many

linq,many-to-many
So I have Business Jobs (many per business) JobApplications (many per job) I just want to count the total number of Applications for a business. But I dont seem to be able to go Business.Jobs.JobApplications if I use Business.Jobs.SelectMany(l => l.JobApplications is accessible from there but I dont understand how...

How to join many to many in createQuery()

symfony2,join,doctrine,many-to-many,createquery
I'm working on my portfolio, and I got a page where I show my project. I created 2 cayegorie for now: Programmation and artistic. Each of my project can be a programming project, an artistique project or both. There for, I made a table project and a table categorie and...

How I can delete grails domain object with many-to-many relationship?

grails,delete,many-to-many,relationship
class Client { String name String surname String address static hasMany = [departments:Department] } class Department { /*static constraints = { }*/ String depName String location static hasMany = [clients:Client] static belongsTo = Client } def deleteDepartment(){ def values = params.list('departments') def checkedID = new Integer[values.size()] for(int i=0; i<values.size(); i++){...

Many-to-many checking in Twig with Symfony2

symfony2,many-to-many,twig
While editing I need to check the boxed that already have relation, I came up with this solution: {% for c in categories %} {% set checked = false %} {% for p in c.posts %} {% if p.id == post.id %} {% set checked = true %} {% endif...

Laravel: many-to-many with shared table

php,mysql,laravel,many-to-many,relationship
I have Locations model which hasMany Employees -- similarly Employees belongsTo Locations This is nice and works well, but then I looked at adding PhoneNumbers. Either a Location or an Employee could have a phone number (office numbers versus personal numbers) Logically: Locations hasMany PhoneNumbers (multiple office lines) and Employees...

How to add an entry to ManyToManyField in Django?

django,django-models,many-to-many,manytomanyfield,junction-table
I have the following models: class Vote(models.Model): cmt = models.ForeignKey(Comment) user = models.ForeignKey(User) vote_type = models.SmallIntegerField(default=0) # vote_type is +1 for upvote & -1 for downvote class Comment(models.Model): uuid = models.CharField(max_length=40, default='random') user = models.OneToOneField(User, primary_key=True) # ForeignKey('User') text = models.CharField(max_length=300, null=True) votes = models.ManyToManyField(User, through='Vote', related_name='votes_table') If I wasn't...

Hibernate: Remove Item From Collection Without Initialazing

hibernate,collections,many-to-many
I'm having troubles with an Hibernate Many To Many Collection. When i try to remove an item from the relation, hibernate loads the entire collection (is too big). Here is an example: supose A has many to many relation with B public class A { @ManyToMany(cascade = { CascadeType.MERGE, CascadeType.PERSIST,...

Assigning id's from another table to input using nested forms in Rails 4

ruby-on-rails,forms,ruby-on-rails-4,nested,many-to-many
I'm a few weeks in to my first experience with Rails / web development in general and have come across a snag I can't seem to find on overflow or work out. I feel that I'm almost there but not quite... I'm developing a staff site for a charity, and...

Flask-Sqlalchemy, Primary key for secondary table in many-to-many relationship

python,postgresql,flask,sqlalchemy,many-to-many
I am trying to build simple many-to-many relationship using Flask-Sqlalchemy for Postgresql Database: from app import db from sqlalchemy.dialects.postgresql import UUID authors_books = db.Table( 'authors_books', db.Column('id', UUID(as_uuid=True), primary_key=True), db.Column('author_id', UUID(as_uuid=True), db.ForeignKey('authors.id')), db.Column('book_id', UUID(as_uuid=True), db.ForeignKey('books.id')), ) class Author(db.Model): __tablename__ = 'authors' # Fields id = db.Column(UUID(as_uuid=True), primary_key=True) first_name =...

Grails with custom many to many relationship, relational table with parameters

grails,spring-security,many-to-many
I have domains: Comments, Secuser and Rating. I would like that each comment can be rated once by SecUser +1 or -1. In the view of related comments (to the domain discussion) I would like to have a button to up-vote or down-vote the comment and refresh the view. The...

What is the correct CascadeType in @ManyToMany Hibernate annotation?

java,hibernate,annotations,many-to-many,cascade
I am trying to model a transient operations solution schema in Hibernate and I am unsure how to get the object graph and behavior I want from the model. The table structure uses a correlation table (many-to-many) to create lists of users for the operation: Operation OperationUsers Users op_id op_id...

MySQL delete and remove from many-to-many table in one transaction

php,mysql,transactions,many-to-many,model-associations
Is it possible to delete from association table (many-to-many) and insert same row to it in the same transaction? This is my association table: CREATE TABLE image_tag ( imageid bigint(19) NOT NULL, tagid bigint(19) NOT NULL, PRIMARY KEY (imageid, tagid)); ALTER TABLE image_tag ADD INDEX FKimage_tag587679 (tagid), ADD CONSTRAINT FKimage_tag587679...

many to many powerpivot relationship

many-to-many,relationship,powerpivot,powerview
I have 2 data sets which i would like to create relationships for (there is a third i would like to join but the first 2 are priority). They all have a common link that is design_ID. I did have a picture showing what i have tried. but i do...

EF Code First 6 and many-to-many with entity mapping

entity-framework,ef-code-first,many-to-many,entity-framework-6
Following the example in this question: How to create a many-to-many mapping in Entity Framework? I would like to have a table mapping where I can add or remove many-to-many relationships without having to go through the Media or Contract entities. Essentially, I would like to have: public class Media...

many to many association mass assign checkboxes ruby on rails 4

ruby-on-rails-4,checkbox,many-to-many,has-many-through,jointable
what i want to accomplish it's almost exactly the same as this! railscast tutorial but can't get it to work.I have a courses table and a enrollments table they have a many to many relation so i have a join table called "courses_enrollments" i'd like to be able to add...

How do I avoid saving duplicate records when saving objects with many to many relationships?

c#,entity-framework,asp.net-mvc-5,duplicates,many-to-many
I'm trying to wrap my mind around this but I could really use some pointers. Currently I have a many-to-many relationship between two entities and my application is working fine. However, I'd like to modify how my data gets stored regarding the tags table. I would like for only unique...

Mysql Many to Many with Mapping table return one row and concatenate the values that would cause duplicate rows

php,mysql,many-to-many,concatenation
I am using mysql and have three tables one for events one for officials and a mapping table between. How would I query so that the following takes place: One single row per event Concatenate the multiple values for officials into the corresponding single event row. Tables are structures as...

Clear many to many on multiple objects in Django

python,django,many-to-many
Is there any way to bulk clear object relations before delete() method? I've got a model: class Man(models.Model): girlfriends = model.ManyToManyField('Girl') and want to delete all "Man" objects in views.py: def delete_all_objects(request): men = Man.objects.all() #trying to clear objects. getting an error men.girlfriends.clear() men.delete() return HttpResponse("success") Getting error: 'QuerySet' object...

Rails - Many to Many association (Adding User to Groups) SQLite

ruby-on-rails,ruby,many-to-many,has-many-through
I have a Many-to-Many relationship here. class Project < ActiveRecord::Base has_many :memberships has_many :users, :through => :memberships end class Membership < ActiveRecord::Base belongs_to :project belongs_to :user end class User < ActiveRecord::Base has_many :memberships has_many :projects, :through => :memberships end These are the three models that I have. I want to...

Sequelize.js many to many eager loading

database,node.js,many-to-many,sequelize.js,eager-loading
I have 2 models: User and Team There are multiple kinds of users (in this case Mentors and Moderators) which are differentiated using an attribute in the User model(). The associations between User and Team are as below: User.hasMany(models.Team, {as: 'Mentors', through: models.TeamMentor, foreignKey: 'mentorId'}); User.hasMany(models.Team, {as: 'Moderators', through: models.TeamModerator,...

“Object reference not set to an instance of an object error” when adding an item with Entity Framework Many-To-Many relationship

c#,linq,entity-framework,many-to-many
I am having an error about which I have no idea since it does not provide any details other than saying Object reference not set to an instance of an object error. I have a many-to-many relationship between Person and Course class, as defined below. When I attempt to add...

Yii2 extending Gii CRUD with many-to-many form elements

php,many-to-many,yii2
I have the following 3 tables: Rule -id -name CombinedRule -id -name RuleCombineMapping -id_rule -id_combine I generated a CRUD for Rule and for the CombinedRule table. Inside the CombinedRule model class I created a mapping the class looks like the following: <?php namespace app\models; use Yii; /** * This is...

How to make hibernate unidirectional many-to-many association updateable?

java,hibernate,many-to-many,updates
I have two entities - Category and Attribute. Category can have multiple related attributes, and Attribute can be related to any number of categories. Association should be available only on Category side - Attribute objects are not aware of categories they are related to. So I model this association as...

Use multiwidget for many to many field with readonly additional data

django,django-admin,many-to-many,django-multiwidget
I've the following models: class Exam(models.Model): participants = models.ManyToMany(settings.AUTH_USER_MODEL, through='Participation') class Participation(models.Model) user = models.OneToOneField(settings.AUTH_USER_MODEL) exam = models.ForeignKey('Exam') specific_number = models.PositiveIntegerField(editable=False) As you can see, the data I'm storing in intermediary model is readonly. It's generated automatically by the system when an instance is created. So I'd like to be...

Column does not exist - Hibernate ManyToMany association class

java,hibernate,jpa,orm,many-to-many
I'm facing the following problem. Imagine this data model: As you can see project_function entity is association many to many entity. Here are my entity classes. PeronalCard: @Entity @Table(name = "personal_card") @XmlRootElement public class PersonalCard implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional...

Is it possible to combine many-to-many relationships with one-to-many relationships in a single query?

php,mysql,many-to-many,one-to-many
I have a MOVIE table that includes a many to many relationship with a genre as well as a review table that has a one to many relationship. AKA, a movie can have many genres and a genre can have many movies. A movie can have many reviews. My problem...

Postgresql Iterate over an array field and use the records for another query

sql,arrays,postgresql,many-to-many
I'm trying to iterate over an array field in order to use every record as a parameter to query and finally join all results, but I need help to get it. I have a table with an array field called fleets and it can have one or more values ie....

How to self join a many to many table in cakephp 3?

model,many-to-many,cakephp-3.0,self-join
I try to self join my table user to get parent-child associations but it didn't work here is my association in the Users model: $this->belongsToMany('Parents', [ 'className' => 'Users', 'joinTable' => 'users_users', 'foreignKey' => 'id', 'targetForeignKey' => 'parent_id' ]); $this->belongsToMany('Childs', [ 'className' => 'Users', 'joinTable' => 'users_users', 'foreignKey' => 'id',...

Symfony ManyToMany delete record

php,symfony2,doctrine,many-to-many
I was trying to update a many to many relation between "book * <- -> * tag". For that, I first wanted to delete all current related tags of a book - to add afterwards again the changed /entered tags. Deleting all tags of a book is working, but when...

hibernate does not insert to join table automatically

java,hibernate,many-to-many,persistence
I'm working on a java spring mvc application with hibernate. I have two Entities Acl and AclGroupand These two entities have Many to Many relationship with a join table. But, when I save an AclGroup object, hibernate doesn't insert any record in join table and just inserts into AclGroup table....

openerp many2many default disappear

many-to-many,openerp,default
I have a form which I pass some invoice ids through context by an act_window. Invoices are set as default in an many2many field (I tried both using a default function and overriding the default_get function), but when I add a record on another one2many field in the same form,...

Ruby on Rails: adding association based on user input, many to many using :through, create and destroy method errors

ruby-on-rails,ruby,many-to-many,has-many-through
I'm trying to build a simple project management app where a user can be a member of many projects and a project can be a member of many users. This many to many relation is represented in my models below: #project model class Project < ActiveRecord::Base has_many :memberships, dependent: :destroy...

How to build the gridview from 2 tables and save co-ordinates mapping in 3'rd table in asp.net web form?

asp.net,sql-server,gridview,many-to-many
I am having Component table, Role table, and ComponentRoleMapping table in database. Please look at the image below. I want to populate the column Component names as first column filled with all rows and roles should be the first row of grid from Role table. All cell have to have...

How to define many to many with attributes in Entity Framework

c#,.net,entity-framework,many-to-many
I try to model many to many relationship between Car and Employee where the info about when the car was used are held. So I need a class inbetween which will hold those additional attributes. The SSCCE: I have Person class: public class Person { public int Id { get;...

database Junction/association table with more data fields

sql,database-design,many-to-many
I am not a fan of having more than two fields (eg: pk1 & pk2) in a junction/association table. I do have a situation, however, and not sure what would be the best approach to resolve it. Table 1: Contract (id, price, description) Table 2: Person (id, firstname, lastname) Table...

Django complex Query through database API

django,database,python-3.x,many-to-many
I am using django 1.7, python 3.4 I have a model class called 'EnterpriseProfile' which is in one to one relationship with a class named 'Enterprise'. Also there is another model 'User' which has a many to many relationship with 'Enterprise'. Now, in 'EnterpriseProfile' model I want to create a...

Yii behaviors won't save data

php,yii,many-to-many,behavior
I'm trying to save relations in third table 'Relations'. Here's code: Controller save action: $relations = $_POST['VideoCaptions']['countries']; $model->attachBehavior('ManyToManyRelationBehavior', array( 'class' => 'ManyToManyRelationBehavior', 'modelNameRelation' => 'Relations', 'firstField' => 'video_captions', 'secondField' => 'video_countries', 'relationList' => $relations, )); ManyToManyRelationBehavior class afterSave action: if (is_array($this->relationList)){ $model_ = $this->modelNameRelation;...

How to use Many to Many Relationship posts#show In ruby on rails

ruby-on-rails,ruby-on-rails-4,many-to-many
in Teams#model class Team < ActiveRecord::Base has_many :postteams has_many :posts, :through => :postteams end in Post#model class Post < ActiveRecord::Base has_many :postteams has_many :teams, :through => :postteams accepts_nested_attributes_for :postteams end In Postteam Model class Postteam < ActiveRecord::Base belongs_to :post belongs_to :team end Through these relations, i finally succeed to make...

MySql many to many search

php,mysql,many-to-many,laravel-5
I'm having some issues wrapping my head around a many to many lookup. I've got the following tables: mysql> desc tags; +------------+------------------+------+-----+---------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------------------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment |...

Flask/SQLAlchemy - Difference between association model and association table for many-to-many relationship?

flask,sqlalchemy,many-to-many,flask-sqlalchemy,model-associations
I started learning this stuff from the Flask Mega Tutorial. When he gets into Many-to-Many relationships, he creates an association table like this: followers = db.Table('followers', db.Column('follower_id', db.Integer, db.ForeignKey('user.id')), db.Column('followed_id', db.Integer, db.ForeignKey('user.id')) ) As I was searching for ways to add some metadata regarding a specific association between models, I...

MYSQL Select many to many

php,mysql,pdo,many-to-many
I was working with two tables: comment, user comment table had a recipient field holding a user id Now we must change the comment/recipient to a many-many relationship as multiple users can receive the same comment, so I added a link table, comment_recipient However, now I'm not sure how to...

Limit number of calls in using Parse

android,database,many-to-many,realm
I'm building my first application with a backend. General info The app allows users to upload a place, attach tags to it, pictures, etc. Dbs I'm using Realm as an offline Db & Parse.com as online Db. Example I'm building the database model and trying to link all many-to-many relations....

Django Form for ManyToMany fields

python,django,many-to-many,blogs
I have to design a form for add a new post in my blog. Model.py class Category(models.Model): title = models.CharField(max_length=200) ... ... def __unicode__(self): return self.title class Post(models.Model): title = models.CharField(max_length=80) pub_date = models.DateTimeField() text = models.CharField(max_length=140) ... categories = models.ManyToManyField(Category, blank=True, null=True, through='CategoryToPost') def __unicode__(self): return self.title class CategoryToPost(models.Model):...

LINQ many to many relationship - get a list of grouped objects

c#,linq,group-by,many-to-many,left-join
I have a bit of a complicated one (for me anyway): I have 2 entities in a many to many relationship. Projects {Project_Id, ProjectName} Users {User_Id, UserName} Projects-Users {Id, Project_Id, User_id} A project can be assigned to more users. Now I want to retrieve the List of all projects (listed...

parse.com many-to-many get list of Pointer ID with Javascript

javascript,pointers,parse.com,many-to-many
I have a problem with a many-to-many relationship on parse.com. First of all I have two classes (Groups and Users) and a class (UserInGroup) to realize the m-to-m relationship. Class structure: Groups: objectId(string) -- GroupName(string) -- ... Users: objectId(string) -- UserName(string) -- ... UserInGroup: objectId(string) -- Group(Pointer< Groups>) -- User(Pointer<...

django - many-to-many and one-to-many relationships

django,database,table,many-to-many,many-to-one
I am working in django, am planning a database for rides for users. each User can be on multiple Rides (over time) and each Ride can have multiple Users (passengers) in it. Also, for each Ride there has to be only one Driver (also a User) so I think I...

Mapping from many-to-many in database to one-to-many in domain

.net,many-to-many,entity-framework-6,one-to-many,ef-fluent-api
I have a mapping challange in Entity Framework. In the database I have a many-to-many relation between two tables with a intermediate table with the PK of the both as bellow: I need to map this relation to a one-to-many domain entities relation as bellow: How can I map this...

one account have many friend who have same attribute of user ? how to implement it in DB & how it look like in ER diagram

mysql,database-design,many-to-many,entity-relationship,self-reference
one account have many friend who have same attribute of user ? how to implement it in DB & how it look like in ER diagram i'm trying to build simple DB project where i have user with (email,password) each user have many friend where the friend also a user...

Has many through stop printing the entire object after loop

ruby-on-rails,ruby-on-rails-4,many-to-many,views,has-and-belongs-to-many
I am practicing has_many through but I am stuck when the looping through the contents. It displays the whole object and not just the item want. Models: class Appointment < ActiveRecord::Base belongs_to :physician belongs_to :patient end class Physician < ActiveRecord::Base has_many :appointments has_many :patients, through: :appointments end class Patient <...

Asserting for presence of added objects in Django ManyToMany relation

django,many-to-many
I have the following model; class Station(models.Model): name = models.CharField(max_length=50) address = models.TextField(default='') owner = models.ForeignKey(User,default='') members = models.ManyToManyField(User, related_name='members') Now after the following code; user1 = User.objects.create_user(username="username1", password="password1") user1.save() user2 = User.objects.create_user(username="username2", password="password2") user2.save() user3 = User.objects.create_user(username="username3", password="password3")...

'where' condition in has_many_through in kohana

php,many-to-many,kohana,has-many-through
I have two models Illness and Symptom: Illness class Model_Illness extends ORM { //protected $_db_group = 'default2'; protected $_table_name = 'illnesses'; protected $_has_many = array( 'symptoms' => array( 'through' => 'symptoms_illnesses', 'foreign_key' => 'illness_id', ) ); Symptom class Model_Symptom extends ORM { //protected $_db_group = 'default2'; protected $_table_name = 'symptoms';...

Why does Entity Framework create a new entity when I try to associate an existing one?

entity-framework,many-to-many
I have a many-to-many relationship (Users to skills), and when I try to associate an existing skill to a user, it always creates a new one. User: public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType...

I need help for Many to Many relation database

mysql,codeigniter,many-to-many
I am Using CI with hmvc.. I have 3 tables: Table 1: s_id | s_name | s_date Table 2: n_id | n_name | n_date Table 3 contains the relation between table 1 and table 2: s_id | n_id I want to fetch values in table 1 or table 2 by...

I need the results from these two queries to be combined into one statement

sql,many-to-many
The set up is a contact table, employee table, and an Employee_contact table with a many to many relationship. I want to know how to combine these two queries into one for a combined result set. SELECT FirstName, LastName, (ContactNumber) AS Home FROM Employees AS E JOIN Employees_Contacts AS EC...

Adding column in Entity Framework 6.1 - Many-To-Many - Code First

c#,entity-framework,ef-code-first,many-to-many,code-first
Just as an example I'm using the code from this article on codeproject: http://www.codeproject.com/Articles/234606/Creating-a-Many-To-Many-Mapping-Using-Code-First Im trying to do something similar in my code but I also want a quantity property, so: One course can have many persons One Person can have many courses Each person can choose a quantity of...

Joins and Many to Many Relationship in mySQL

php,mysql,sql,database,many-to-many
So I have a database consisting of posts and categories using the following tables posts (PostID, PostName, PostCategory) categories (CategoryID, CategoryName) then I have another table which is there to join the two together as follows posts_categories (Posts_Category_ID, PostID, CategoryID) I would like to know how to create an SQL...

Why is persist method called twice?

java,jpa,many-to-many,eclipselink
In my service level I create a new object from Entity1 class and persist it and then call setters on it. but after all, another object from Entity1 will be created and inserted in database( so I will have two rows in Entity1 table inserted in database instead of one)....

ios/xcode/coredata: Data model for many to many relationships

ios,core-data,many-to-many
IOS newb from mysql background working on an app that ties into a web server backend. If I have two entities or objects enjoying many to many relationships such as item and tag, in MYSQL I would have three tables, the table of items, the table of tags and a...

Query a many-to-many relationship with linq/Entity Framework. CodeFirst

c#,linq,entity-framework,many-to-many
How can I query a many-to-many relationship using Entity Framework code first and linq? The problem is that EF create automatically the relation table. So, I don't have it in my context. This is the relational model: I need a list of Articles for a specific Category_Id, basically replicate something...

Django many-to many filter field

python,mysql,django,django-views,many-to-many
I want to add into the list if the region, contains that country, its a relation of M2M between the Region and Country models. i cant get to the attribute of the country code it says that "colon expected". what is missed in the if condition? views.py notification = Notification.objects.filter(**condition)....

Rails HABTM or has_many?

ruby-on-rails,many-to-many,relational-database
I have two models: Person, and Property. In the Person model I have a field which stores the role of the person(tenant, owner, admin, contractor, etc). Since each property will belong to an owner and potentially have one or more tenants, I thought this would be a good opportunity to...

Rails 4 many-to-many associations nightmare

ruby-on-rails,ruby,activerecord,many-to-many,associations
I'm trying to set up a has_many :through association between three models: Trip, Location and LocationsTrip, but the associations just don't seem to be picking each other up. I set up my associations: class Trip < ActiveRecord::Base belongs_to :user has_many :locations_trips has_many :locations, :through => :locations_trips accepts_nested_attributes_for :locations_trips, :allow_destroy =>...

Hibernate : Update many-tomany intermediary table on Delete

java,hibernate,many-to-many
I am fairly new to Hibernate and do not fully understand how I should proceed to update an intermediary table. I have a ManyToMany relationship between two tables : conferences & publications POJO Publication.class : private List<Conference> conferences; ... @ManyToMany(targetEntity = Conference.class, cascade = { CascadeType.PERSIST, CascadeType.MERGE }) @JoinTable(name =...

JPA many to many relation not inserting into generated table

mysql,spring,hibernate,jpa,many-to-many
I have a many-to-many relation in my project and although I'm able to write in my two Entities table, the relational table does not get anything written. Here's how I'm declaring this using JPA annotations: Professor.java @Entity @Table(name = "Professor") public class Professor implements Serializable { private static final long...

Many-to-many relationship with compound primary key constraint

mysql,foreign-keys,many-to-many
I got a requirement for many-to-many relationship design in DBMS with other constraints. There are two tables, t1 and t2 where t1.id and t2.id are primary keys respectively. t1 and t2 has many-to-many relationship, so a natural design is to add a third table t3 with foreign keys. e.g., t3:...

CakePHP select many to many (HABTM) records

php,cakephp,many-to-many,has-and-belongs-to-many
after create a many to many (HABTM) relationship between 2 classes (as code bellow) I was expecting to see results including the related records but for some reason this is not happening. Models App::uses('AppModel', 'Model'); class NewsCategory extends AppModel{ public $hasAndBelongsToMany = array('News'); } App::uses('AppModel', 'Model'); class News extends AppModel{...

hibernate - cascading type persist for many to many relationship

java,hibernate,many-to-many,hibernate-cascade
I have two classes Policy and Acl. They have a ManyToMany relationship in them. // Policy public class PolicyEntity { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) @Column(name = "POLICY_ID") private int policyId; @Column(name = "POLICY_NAME") private String policyName; @ManyToMany(cascade = CascadeType.PERSIST) @JoinTable(name = "POLICY_ACL",[email protected](name = "POLICY_ID"), [email protected](name = "ACL_ID")) private List<AclEntity> aclList...

Having trouble with mysql relationships?

mysql,many-to-many,relationship,one-to-many
I need two tables, one that shows a one to many relationship using three tables, and another table that shows a many to many relationship. I have managed to do the first 2 with were a query involving just one table, and a one to many involving 2 tables. One...

Update many to many association table with derived field

python,flask,sqlalchemy,many-to-many,flask-sqlalchemy
I'm writing a RESTful API using Flask, Flask-SQLalchemy and Flask-Restful. I have models for Contact and Category, and a helper table for mapping a many-to-many relationship between them. contactgrouping = db.Table('CONTACT_GROUPING', db.Column('catid', db.Integer, db.ForeignKey('CATEGORY.catid')), db.Column('contactid', db.Integer, db.ForeignKey('CONTACT.contactid')), db.Column('clientid', db.Integer, db.ForeignKey('CLIENT.clientid')), ) class Contact(db.Model): __tablename__ = 'CONTACT' contactid = db.Column(db.Integer, primary_key=True)...

System.NullReferenceException when Inserting a new item for many-to-many relationship in entity framework

c#,entity-framework,many-to-many,ef-fluent-api
When adding an item for many-to-many relationship, I receive this error An exception of type 'System.NullReferenceException' occurred in gEchoLu.dll but was not handled in user code with no further details. Here is the code that throws the exception: protected void btn_AddMembers_Click(object sender, EventArgs e) { gEchoLuDBContext _db = new gEchoLuDBContext();...

How to setup custom join table in Entity Framework

entity-framework,many-to-many
When setting up a many-to-many relationship with Code First approach, by default the join table only includes 2 columns (FK to PK of the 2 tables). 1) Is it possible/How can I setup a join table that will include some additional fields, and 2) how do I fill these values...

Deleting records in many to many relation

c#,many-to-many,deleting
When I delete movie i get error about foreign foreign key. And my question is How to delete all records from the table MovieActor with ID movie that I want to remove? And at the end movie from Movie table? its impossible to write code that would do this automatically...

Many to Many Query Buider Symfony2

symfony2,orm,many-to-many,query-builder
I have two entities. Category and Product. They mapped ManyToMany. class Category { ... /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; ... } and Product class class Product { ... /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * *...

How to design a history for n:m relations

sql,plsql,many-to-many
Problem: I have a n:m relation between a table A and another table B and it is required to have the complete history of this relation, in other words I must be able to reproduce the status of any point the past. Ideas: My first attempt is to dissect to...

find many to many with no relation

mysql,sql,database,many-to-many
I have an items table, a tags table and a reletations table. I need to find no tagged items. With this (working) query I find the tags number for each item: SELECT i.id, i.text, COUNT( ti.item ) AS count FROM items AS i JOIN topic_item AS ti ON ti.item =...