Rectangle 27 3

Don't clear the skills. What that's actually doing is telling Entity Framework to remove all existing relationships from the join table and then add entirely new relationships back.

When updating M2M relationships, you can't just set the property. You need to first remove any deselected items, and then add new items, while leaving existing items alone:

public ActionResult Edit(int id, TeacherViewModel model)
    var teacher = db.Teachers.Find(id);
    if (teacher == null)
        return new HttpNotFoundResult();

    if (ModelState.IsValid)
        teacher.firstname = model.lastname;
        teacher.lastname = model.lastname;
        teacher.image = model.image;
        teacher.campusId = model.campusId;

        // Remove deselected skills
        teacher.skills.Where(m => !model.skillIds.Contains(m.Id))
            .ToList().ForEach(skill => teacher.skills.Remove(skill));

        // Add new skills
        var existingSkillIds = teacher.skills.Select(m => m.Id);
        db.Skills.Where(m => model.skillIds.Exclude(existingSkillIds).Contains(m.Id))
            .ToList().ForEach(skill => teacher.skills.Add(skill));

        return RedirectToAction("Index");

    return View(model);

As you can see, I've added a view model, which you should always be using anytime you feel the need to add Bind. Just don't use Bind ever. I'm also passing the teach id as part of the URL. You should not be posting the id ever. Never include anything in your post body that you don't want to be potentially modified. I use that id to select the teacher fresh from the database. You should never directly save an entity that was posted. Then, there's the new code which removes deselected skills and adds newly selected skills.

c# - MVC Entity framework update Many to Many relationship - S...

c# entity-framework
Rectangle 27 0

I managed to solve this problem using the advice of Java Ka Baby. The issue was actually not in my Model classes; the problem lay within the Controller. Specifically, I was saving the entities in the wrong order. Once I realized that using the @ElementCollection annotation on the Map<Long, Foo> produced the same effects as the join table I was manually specifying, I tried I thought experiment where I re-thought how I was saving my entities.

In the code I posted above, you can see in the FooSystem constructor that two Foo objects, f1 and f2, are put into fooMap before the Foo objects are persisted. I realized that if f1 is not in the database when it is put into the map, how is JPA able to use its ID as a foreign key in the join table?

If you can see where I'm going with this line of reasoning, you can see that the obvious answer is that JPA is not able to accomplish this amazing feat of using a foreign key to reference a nonexistent key. The bizarre thing is that the Play! console did not note any errors at all for the original code I posted, even though it was not correct at all. Either the framework swallowed every Exception thrown during the process, or I've written code that should produce an Exception.

So to fix the problem, I persisted the Foo entities before any operations were performed on them. Only then did I put them into fooMap. Finally, once fooMap was populated, I persisted the FooSystem entity.

Here is the corrected TestController class:

package controllers;

import javax.persistence.EntityManager;
import models.test.Foo;
import models.test.FooSystem;
import play.db.jpa.JPA;
import play.mvc.Controller;

public class TestController extends Controller
    public static void index() {
        EntityManager em = JPA.em();
        FooSystem fs = new FooSystem();
        Foo f1 = new Foo(fs);
        Foo f2 = new Foo(fs);;;
        fs.put(f1.getId(), f1);
        fs.put(f2.getId(), f2);;

And, since I changed FooSystem, here is the final code for that class:

package models.test;

import java.util.HashMap;
import java.util.Map;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import play.db.jpa.Model;

public class FooSystem extends Model
    private Map<Long, Foo> fooMap = new HashMap<Long, Foo>();

    public FooSystem()

    public Map<Long, Foo> getFooMap()
        return fooMap;

    public void put(Long l, Foo f)
        fooMap.put(l, f);

hibernate - How do I use JPA to persist a Map (java.util.Map) object i...

java hibernate jpa map playframework
Rectangle 27 0

UPDATE: i had solved my sorting problems in the following way: I changed my DataSet in the model and joined the related table to the Main-Table(ERP_Charge). I added the columns to the Datatable(f.e. CustomerName) that i want to sort. But i did that without saving it in the configuration wizard of the DataAdapter, because that would delete all Update-,Delete- and InsertCommands. Hence i changed only the SelectCommand with the one that was generated from the Wizard. Therefore i kept the benefit of my Datamodel with the ability to sort for columns of related tables. Maybe queries are a little slower now because of the joins but it works for me. - Sort a GridView Column related to other Table - Stack Overfl... gridview sorting
Rectangle 27 0

I think I understand you question, and you're correct in assuming that you cannot use the .users method whether or not the project model is saved. The reason for this is that in defining an association in Project (ie. has_many :users, through: :project_participations, inverse_of: :projects) you're telling rails to read the users attribute out of the database via the project_participations join table and when you haven't saved the project you have nothing to read out of the database.

In order to add a User to your project in a particular role you will need to create a new ProjectParticipation model which you will then associate to your project. If you then remove the users association and write your own users method you should be able to access your collection of users regardless of whether or not the project has been saved.

class Project < ActiveRecord::Base
    has_many :project_participations


    def users
        project_participations.collect { |pp| pp.user }
u = Users.create
p =

pp ={user: u, project: p, role: 1})
p.project_participations << pp

This works for now but I think this is not the cleanest solution. (For example because it is slow to collect every user in a separate query etc). I'll try to work with this and see how far I come and then maybe accept the answer / add new comments.

Please do add comments if you find a better way.

ruby on rails - Update attributes on has_many through associations and...

ruby-on-rails validation activerecord has-many-through
Rectangle 27 0

Save via the join table model

The solution should be pretty simple, for that type of association you'll have to save via the join table model (even if you don't save additional data on the that table):


That way the ORM can properly save the belongsTo associated data, and create an appropriate record in the join table, using foreign key values obtained from the save operations for the associated data.

Sorry, it took me a while to get back to you. The genius I am, I messed up my Ubuntu install for like the millionth time by accidentally setting a sudo chmod -R on my var folder. Sigh. Anyway, this works like a charm. Thanks so much!

php - CakePHP Saving a new normalized HABTM model and using it in the ...

php cakephp has-and-belongs-to-many
Rectangle 27 0

You can create Recommendation and Like models and use them to join the Users with Movies. Or just a single model called don't know how(RecommendLike?), if you really wish to save on one table. And then:

  has_many :recommendations
  has_many :movies_recommended, :class_name => "Movie", :through => :recommendations
  has_many :likes
  has_many :movies_liked, :class_name => "Movie", :through => :likes

But then how do I add a relationship between a User and a Movie with a specific type then? ( I am specifically referring to how I could populate movies_users)

My suggestion is a replacement for your table movies_users as you can't have any extra attributes in join-tables used in has_and_belongs_to_many. There are actually different approaches in this case. You can have recommended_movies_users and liked_movies_users if you insist on using has_and_belongs_to_many.

I would always prefer to have less tables. your approach creates 2 additional models which I find to be a bit overkill

I wouldn't save on tables if it makes the code cleaner. But anyway, you can't get away with the existing tables. At least, you have to create one extra table.

So let say I decided to go with RecommendLike and then have an extra column called type (like||recommend). I guess in users it will be has_many :recommendlikes; has_many :movie_recommended, :class_name => "Movie", :through => :recommendlikes, :conditions => { "type" => "recommend" }? and then to save this relationship, I should just create a new Recommendlike and then populate the attribute and save?

activerecord - Rails Many to Many with condition adding new condition ...

ruby-on-rails activerecord has-many-through has-and-belongs-to-many
Rectangle 27 0

Mastering the django ORM. First steps [Python, list, tutorial, begin...

# -*- encoding: utf-8 -*-
# Made by
# This will teach about how use the django ORM

# About

# The django ORM provide a great way to perform CRUD operations
# against a Sql-based database engine. Also, is very easy
# to master.

# Official docs

# Usefull links

import sys
from os import path
import collections
import datetime

sys.path.insert(0, path.abspath(path.join(path.dirname(__file__), '..')))

from utils import printTitle, printSubTitle, printExplain, printTab, printError

printTitle("The django ORM")

printExplain("Is used for perform CRUD operations against a database")
print "And is the foundation of several key parts of the django API, like the admin app"

printTitle("You need to have the proper settings")
print """
Normally, the django ORM will be used inside a django project.

However, for this tutorial, we will use it standalone, without a full
project setup

printSubTitle("Configure the database")
printExplain("First, you need a database")
print """
We will use sqlite, because is the simplest one, also, it work better
for a tutorial like this.

The database will run in memory

from import call_command
from django.conf import settings

if not settings.configured:
            'default': {
                # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
                'ENGINE': 'django.db.backends.sqlite3',
                # Or path to database file if using sqlite3.
                'NAME': ':memory:',
        INSTALLED_APPS=("runnable", )

printTitle("Create the tables from the models")
# This is not normally how is done in django!
# But is the way to use the django ORM outside a django project

printExplain("Now we have the tables/indexed created")
print "Yep, django do it just from the models"

def readCsv(csv_data):
    # A simple utily to read a CSV-like data as namedtuples
    Row = None
    for line in csv_data.splitlines():
        if Row:
            yield Row._make(line.split(';'))
            header = line.split(';')
            Row = collections.namedtuple("Row", header)

# In models exist our objects definitions. It will map to database tables
from models import *
# Some data for testing
# Generated from
from sampledata import ADDRESS, PERSONS

def readPerson():
    for row in readCsv(PERSONS):
        yield Person(

def readAddress():
    people = list(Person.objects.all())

    for i, row in enumerate(readCsv(ADDRESS)):
        yield Location(

printTitle("CRUD operations")

printSubTitle("Create object")
print "Just pass the data as params to the object creation or set the fields"

p = Person(name='Jhon Carter', email='')
p.birthdate =, 10, 1)

printExplain("Django will have a default primary key, called .id. Will be None if new")

print "The ID is ",

printExplain("Save single object with .save")

printExplain("Django will auto-update the ID field, the default primary key")

print "The ID is ",

printSubTitle("Read object")
print "You can get the object by Id or any of the fields"

print "Person with id = ",, '?', Person.objects.get(
print "Person with name = Jhon Carter ?", Person.objects.get(name='Jhon Carter')

printSubTitle("Update object")
print "To update a object, simply change the fields values and save it again"

print "Old email=", = ''

print "Person with email = ?", Person.objects.get(email='')

printSubTitle("Delete object")
print "Just call the .delete method on the object you want gone"

print "Person with id = ",, '?'


except Person.DoesNotExist, e:
    # This is the kind of exception if used get and not object is found

printTitle("Let's import some data")
printExplain("Perform INSERTS in bulk")


printTitle("Making queries")
printExplain("So far, we are using the .objects property. Is called a manager in django")
print "And is our interface to perform queries against the model"

printSubTitle("Counting objects")

print "Exist %d persons" % Person.objects.count()
# This is done in the database

printSubTitle("Get all the objects")

allPeople = Person.objects.all()

printExplain("This return a queryset")
print """
Querysets are LAZY and composable, so the query is not yet executed.

Django wont actually run the query until the QuerySet is evaluated...
like for example for iterating or transforming to a python list.

By the way, you can slice a queryset like a python list and django will
perform a efficient LIMIT and OFFSET clause in the database

print "Evaluate the QuerySet: ", list(allPeople)

print """
Is better to filter the data to the one you actually need.

The database engine will (normally) be better at acces data than python alone
specially if the data is large, the database is in other computer and it have
the proper indexes

printExplain("To filter, put the field name + __ + lookup")

peopleStartWithA = allPeople.filter(name__startswith='a')

print "People that name start with 'A'", list(peopleStartWithA)

justMona = allPeople.filter(name__exact='Mona Stevenson')
# This is case sensitive. Use __iexact for case insensitive
# Is equivalent to
justMona = allPeople.filter(name='Mona Stevenson')

print "Exactly 'Mona Stevenson'", list(justMona)

eduAccounts = allPeople.filter(email__contains='.edu')

print "People with .edu mails accounts ", list(eduAccounts)

lowIds = allPeople.filter(id__lte=50)
# Also you can use gt (>), gte (>=), lt (<)

print "People with IDs <= 50 ", list(lowIds)

generartion2014 = allPeople.filter(birthdate__year=2014)
# Also you can use __week_day, __hour, __minute, __second, __month & __day
print "People born in the year 2014 ", list(generartion2014)

printExplain("You can chain filters..")

gen2014edu = generartion2014.filter(email__contains='.edu')

print "People born in the year 2014 with .edu mails accounts", list(gen2014edu)
# Not very logical...

printSubTitle("Slicing a queryset")
print "Remember that you can slice a queryset, and it will do the slice on the database engine"

print "Only the 5 ", allPeople[5]

print "Only the first 5 ", allPeople[:5]
print "Only the from 5 to 10 ", allPeople[5:10]

printExplain("Let's add some address as a ForeignKey to Person")

printSubTitle("You can query it normally")

tanzaniaAddress = Location.objects.filter(country='Tanzania')

print "Address that belong to tanzania ", list(tanzaniaAddress)

printSubTitle("Order data")

printExplain("Order the data directly on the database")

locationOrdered = Location.objects.order_by('country', 'state', 'city')

print "Address ordered by country/state/city ", list(locationOrdered)


printExplain("But the real power is joining data on the relation")

peopleOnAntarctica = Person.objects.filter(location__country='Antarctica')

print "People that belong to Antarctica ", list(peopleOnAntarctica)

printExplain("The django ORM is very powerfull")
print "This was only a taste of it"
printExplain("Remember because is easy, a ORM could mask performance problems")
print """
You need to profile and properly understand what the ORM is doing and
how it relate to your particular database engine.
Python list tutorial beginner Django ORM SQLite database
Rectangle 27 0

Well HATBM works in an very strange way. If you really need HATBM I would suggest NOT changing a model association, but using an interesting shorthand for saving additional data fields in the join table.

I've encountered this a lot of times and this is the best solution: Actually, just for saving your additional fields you can unbind all HATBM relations and add a new hasMany binding "on the fly" pointing to the join model. Firstly you should unbind the existing HATBM relation.

$this->Order->unbindModel(array('hasAndBelongsToMany' => array('Product')));
$this->Order->bindModel(array('hasMany' => array('OrdersPost')));
$this->data['Order']['id'] = '1';
$this->data['OrdersPost'][0]['product_id'] = '15';
$this->data['PostsTag'][0]['price'] = '5000.00';
$this->data['PostsTag'][0]['quantity'] = '1';
$this->data['OrdersPost'][1]['product_id'] = '16';
$this->data['PostsTag'][1]['price'] = '4000.00';
$this->data['PostsTag'][1]['quantity'] = '2';

As mentioned above, HATBM always erases all existing records before inserting new ones. So maybe you should take care about that before you do:


This works when you dont want to change your datamodel, but still need additional functionality. Hope this helps. Original Solution and Credits HERE

php - Saving HABTM with extra fields? - Stack Overflow

php mysql cakephp cakephp-1.3
Rectangle 27 0

CakePHP's model::save() method won't do this for you AFAIK. I think you have to use model::saveAll() and call it on the "with" model. CakePHP is automagically aware of your join table and can modelise it without you having to create a physical model file and class yourself. All you should have to do is format the data array in the format saveAll expects.

I've not tried it, but something like the following should work.

class Item extends AppModel {
  var $name = 'Item';
  var $_habtmData = null;
  function beforeSave() {
    $this->unbindModel(array('hasAndBelongsToMany' => array('Label')));
    $this->_habtmData = $this->data['Label'];
  function afterSave() {
    if (is_array($this->_habtmData) && !empty($this->_habtmData)) {
      foreach ($this->_habtmData['Label'] as $k => $labelId) {
        $this->_habtmData['Label'][$k] = array(
          'item_id' => $this->id,
          'label_id' => $labelId,
          'user_id' => $userId, // Get this from somewhere
      $this->bindModel(array('hasMany' => array('ItemsLabel')));

This is all done in the model (as it should be), so your controller and views stay clean. We do it all in afterSave, so it only tries it if the Item data validates.

Essentially, we temporarily unbind the Item hasAndBelongsToMany Label association in beforeSave, so the HABTM data doesn't get saved and we store the HABTM data in a property of the model, so we can use it in afterSave (although it's probably still available then anyway).

We then bind the "with" model to Item with a hasMany association, and format the data as required by CakePHP's core model::saveAll() method, before finally calling it on the "with" model, passing in the new data.

It should work in theory - good luck and let me know how you get on ;-)

Hey, thanks for the detailed answer. The approach from Matt Curry worked for me and was much simpler. I've got your answer bookmarked as it may be useful if I run into a situation with more complex HABTM data.

database - Saving HABTM records when not all join table columns are fo...

database cakephp has-and-belongs-to-many
Rectangle 27 0

CakePHP 1.x treats HABTM join tables quite 'dumb'; it will remove all existing records and insert new records to replace them. This is a major PITA if your join-table also contains additional data. (It's possible to prevent this from happening by adding some code in your beforeSave() callbacks)

CakePHP 2.1 has an option keepExisting for HABTM relations. This option prevents CakePHP from deleting the records in the JOIN table. If this is a new project I would really advise to use CakePHP 2.x as a lot has improved since CakePHP 1.x.

Some hints on saving data in the join table can be found here;

Ok, thanks thats a good point. No, is an old project witch we update and improve. I solved the problem with the unique => false in the Account Model, but now the model creates duplicate entries. Still a problem

The same technique is possible with CakePHP 1.3, I added the documentation to my answer, however to prevent CakePHP from deleting records, you may have to add some custom logic. If I remember correctly, somebody wrote a plugin for CakePHP 1.3 to handle this kind of situations, can't remember its name right now

model - cakePHP saving entries to join table of existing records - Sta...

cakephp model has-and-belongs-to-many jointable
Rectangle 27 0

<!-- Oracle's "reserved words", which CANNOT be used in custom names. -->
<Keywords fontWeight='bold' foreground='Blue'>

<!-- Oracle's "keywords", which can be used in custom names. -->
<Keywords foreground='Blue'>

c# - WPF AvalonEdit SQL xhsd request - Stack Overflow

c# .net sql wpf avalonedit