FAQ Database Discussion Community


Laravel 5 - Eloquent ORM update all

laravel,orm,eloquent
How can i update everything in a table usins Eloquent? Is there any prepared function for this? I do not want solution with using DB if it is not necessary....

What would be a translation of Ruby On Rails to Sequelize (or other ORMs) in Node.js? [closed]

javascript,ruby-on-rails,node.js,postgresql,orm
What would be some equivalent code I would use if I am switching to Sequelize from Ruby on Rails. If I want to go isomorphic JavaScript I will probably want to use an ORM for Node.js... Before I invest too much time in one versus another are there any recommendations?...

Unable to create one-to-one relationship between entities

c#,nhibernate,orm,nhibernate-mapping
Update 1: Added a link to the code for the entity classes. I have a Vehicle entity (to hold information about a vehicle) and an UploadedDocument entity (represents any uploaded document, in this case (say) the registration papers) being stored in the DB in separate tables (other entities may also...

Odoo Prefilter many2one / many2many / one2many

orm,model,odoo
How can I predefinde/prefilter a many2one field? As example product.category has a type, in my view the user should only be able to select a product.category based on the category type. //field in model category_id = fields.Many2one(comodel_name="product.category", string="ebay Category", required=True) //field in view How can I prefilter the select in...

Axiom Deathmatch: Final Classes

java,hibernate,inheritance,orm
Hibernate Community Documentation : "A central feature of Hibernate, proxies (lazy loading), depends upon the persistent class being either non-final, or the implementation of an interface that declares all public methods. You can persist final classes that do not implement an interface with Hibernate; you will not, however, be able...

Use different model's field with the same value in Django

python,django,orm,django-orm
I have two Django models, and I want to have same-value field in both of them. Basically, when CarModification.engine_status is 'inactive' or 'active', I want to have the same field in Car set to the latest CarModification's field value. class CarManager(models.Manager): def get_queryset(self): # Select engine_status from the latest #...

django model orm, a relationship query issue, hard to describe it

mysql,django,orm
class Topic(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=16,default='') class Post(models.Model): id = models.AutoField(primary_key=True) topic = models.ForeignKey(Topic) time = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=16,default='') now I want to select all the Topics and the last post for the each topic. like this: 1、 topic1      last post for topic1 2、 topic2      last post for topic2...

How can I check if a user is Manager for a specific module in Odoo?

orm,xml-rpc,odoo
I am looking for a way to check if a logged-in user is Manager for a particular Module like 'Point of sale'. Using SQL I am able to check this condition, but can we accomplish the same using ORM? Following is my sql query which is listing the users who...

Translating raw SQL to Eloquent

php,laravel,orm,eloquent
Help me please with this query. SELECT d.date, d.id, d.message, u.username FROM dialogs d JOIN users u ON d.user_id = u.id AND d.is_deleted = 0 WHERE d.id > ? ORDER BY d.id DESC LIMIT 30 There are messages with authors. Now I'm using DB::select for this query, but want something...

Realm.io Query with GroupBy

java,android,sql,orm,realm
I want to group some accounts by month, can i do this with Realm.io? public class Account extends RealmObject { ..... private Date date; } RealmResults accounts = realm.where(Account.class) .beginGroup() .equalTo("date", "MONTH(date)")//<----- wrong code .endGroup() .findAll(); thanks...

how to manually set/persist a primary key in ORM Doctrine2

symfony2,orm,doctrine2
In my table primary key is ISBN so I need to set it manually when adding new Book in form. When adding new Book with ISBN 123, it result in blank ISBN in database. Entity: /** * @var string * * @ORM\Column(name="isbn", type="string", length=45) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private...

Alphanumeric ID in sequelize.js

node.js,postgresql,orm,sequelize.js,alphanumeric
I'm using sequelizejs with PostgreSQL as ORM in my webapp, I want to use alphanumeric ID instead numeric.How can I do that ? Is there some way to do it through sequelize? Or do I want to generate this id separately and then save it into db ? Thanks for...

Multiple foreign keys to the same id. Django. Design Patterns

python,sql,django,orm
I really can't figure out why I can't point by Foregin Key the exactly same id multiple times. I'm trying to use Django ORM to the database that already exists. And it looks like this: I wanted to create model according to that: class TestID(models.Model): id = models.AutoField(primary_key=True) name =...

Peewee throws KeyError when trying to add user defined operator

python,orm,flask,peewee,keyerror
I followed the short guide in the peewee docs on how to add user defined operators, but when I try to do it, it gives me a KeyError. from peewee import * from peewee import OP from peewee import Expression db = MySQLDatabase(app.config['MYSQL_DATABASE_DB'], host=app.config['MYSQL_DATABASE_HOST'], user=app.config['MYSQL_DATABASE_USER'], passwd=app.config['MYSQL_DATABASE_PASSWORD']) OP['MOD'] = 'mod' def...

Get multiple entities from hibernate sql join

java,sql,hibernate,join,orm
I have 4 table: Orders(orderID, orderDate, orderItem (OneToMany)) OrderItem(id, order(manyToOne), book (manyToOne), quantity) Book (id, title, cost) User(id, username, password) Here is my query in SQL: String sql = "SELECT orders.id, book.title, orderitem.quantity FROM orderitem INNER JOIN book ON book.id = orderitem.book_id INNER JOIN orders ON orders.id = orderitem.orders_id WHERE...

Symfony ORM Integrity constraint issue

symfony2,orm
I am working towards the following setup; An Article has many Comments A Comment has only one article At the minute I am successful in not allowing a user to insert a comment into the database which is linked to an Article_Id which does not exist... The problem comes when...

Null result for date object fetched from DB giving sysDate/current date on mapping to Java object

java,database,oracle,date,orm
I fetched data from the oracle database through java code using a query similar to the below: select min(specDate) from table The result is supposed to be of type Date. Since there was no specDate populated for any of the rows in the table, the result was null. I used...

Fuelphp ORM unexpected results when adding to model property

php,orm,model,increment,fuelphp
I have a model that tracks views. It's a very basic model as you can see below. There are currently only 2 methods. One queries the database, and one to add to the views table. The function that checks the table returns either a view object, or null. It's a...

Symfony 2 - How to set relationship between three entities having many to many relationship among them

php,orm,doctrine2,symfony-2.3
I am using Symfony2 for my application and using Doctrine .orm.yml files for relation mapping. I have three entities as follows: user entity which contains id(integer primary key), user_name(varchar) portfolio entity which contains id(integer primary key), name(varchar), user_id (FK from user to identify who created the portfolio) progress entity which...

Odoo 8 what is best way to create records with reference to each other

orm,model,odoo,recordset
After Ive created a method for importing external product categories into my odoo db, I had observed, that the method create of orm model needs a lot of time, when I loop for the reference to each other like this: @api.multi def action_confirm_site(self): account = self ebay_site = self.env['ebay.sites'].browse(account.site.id) call_data...

How to design an application to easily swap Hibernate with JDBC

java,hibernate,jpa,jdbc,orm
First of all, this question may be a duplicate of Moving from hibernate to plain jdbc. But since that question didn't get the answer I'm looking for I'm asking it again. Let's say we have an application working with Hibernate and we decide to change it all back to JDBC...

How to do select with where on second order ForeignKeyField in Python Peewee ORM?

python,database,select,orm,peewee
I'm using the (awesome) Peewee ORM for my database needs and I now constructed a query as follows: OauthCI.select().where(OauthCI.oauth.user.id == 2) So OauthCI has a ForeignKeyField called oauth, which points to a table which in turn has a ForeignKeyField which is called user. Unfortunately, this gives me an error saying:...

CayenneModeler not generating Cayenne.xml

java,data,orm,apache-cayenne
I am learning Apache Cayenne, so I am new to it. I am following the official guide http://cayenne.apache.org/docs/3.0/tutorial.html. I am doing exactly the same as the guide says, but when I save the project, it's generating 2 xml files, instead of 3, and when I run the java app (using...

How to group by projections with Hibernate

java,mysql,hibernate,orm,hibernate-criteria
I need to find a list of students that are in a specific group and located in a specific address along with their phone numbers in their location. My main issue is I can not retrieve phone numbers of each student as a collection. For example if I have student1,student2....

Does Django implement user permissions in databases with models?

python,django,orm,django-admin
In a typical database, admin can assign users and can create tables which can be accessed by only a particular set of users or groups. One can also create queries that can be made by certain users in a database like MySQL. Does Django provide any such functionality or is...

Django object composition with OneToOneField

python,django,design,orm
As noted in other questions, Django experts like Two Scoops recommend explicit OneToOneFields rather than multi-table inheritance to avoid performance penalties of implicit joins. I have tried to follow such an approach, and my design is actually object composition, but have a few questions. All three of these are concrete...

Hibernate criteria accepting %% value

java,hibernate,java-ee,orm,hibernate-criteria
I am using the below Hibernate code to filter workFlowName. crt.add(Restrictions.like("workFlowName", workFlow, MatchMode.ANYWHERE)); // crt is the criteria The problem is when I pass the value to workFlow from web (TextBox).it fetching the value correctly (I am passing sym in text box if fetch 10 records.if i pass the same...

Hibernate MYSQL native query throws ClassCastException

java,mysql,sql,hibernate,orm
Retrieving integer value from table using Hibernate, following exception occurred, java.lang.ClassCastException: java.lang.Integer cannot be cast to pojo.Datasetstatus String q1="SELECT datasetstatusID from datasetstatus where DatasetID='"+meta_dataset+"'"; Query query=session.createSQLQuery(q1); List<Datasetstatus> dobj=query.list(); for(Datasetstatus dobj1: dobj) { System.out.println("Value :: "+dobj1.getDatasetStatusId()); } Pojo class format, public class Datasetstatus implements java.io.Serializable { private Integer...

Caching issue in angularJS application

angularjs,caching,orm,eloquent,slim
I've an admin panel which is a pure angularJS application, which uses REST api for data manipulation. REST api is built using SlimAPI framework and Laravel's Eloquent ORM. I'm facing caching issue in admin panel. Even though if a add new content to the system, it'll not show up in...

Django group by hour

python,django,orm,group-by
I have the following model in Django. class StoreVideoEventSummary(models.Model): Customer = models.ForeignKey(GlobalCustomerDirectory, null=True, db_column='CustomerID', blank=True, db_index=True) Store = models.ForeignKey(Store, null=True, db_column='StoreID', blank=True, related_name="VideoEventSummary") Timestamp = models.DateTimeField(null=True, blank=True, db_index=True) PeopleCount = models.IntegerField(null=True, blank=True) I would like to find out the number of people entering the store each hour. To achieve this,...

Create two ForeignKey to one class

python,django,orm,foreign-keys
I have this problem in this class of the model. class Transferencia(models.Model): descripcion = models.CharField(max_length=200) importe = models.FloatField() tipo = models.ManyToManyField(Tipo) cuentaOrigen = models.OneToOneField(Cuenta) cuentaDestino = models.OneToOneField(Cuenta) monedaReferencia = models.ForeignKey(Moneda) fechaApunte = models.DateTimeField('date published') factura = models.ForeignKey(Factura) def __str__(self): return "Importe: " + self.importe And I've this error ERRORS: walletGestor.Transferencia.cuentaDestino:...

Slim Framework with ORM (Eloquent) connect multiple db

orm,eloquent,slim,multiple-databases
I am using Slim Framework with Eloquent 4.1.x as ORM for a project and need to connect to multiple databases. I followed this link to setup the ORM. But how can I connect to multiple databases by following the given tutorial? In my models I have different files that are...

JPA : How to define @NamedEntityGraph for 3 levels?

java,hibernate,jpa,orm,jpql
I have 3 entities. Branch,Subject,Topic. Branch has list of subjects and Subject has list of topics. Also subjectList and topicList both are lazy. I want to fetch all branch including its subjects and topics in single query. 1. @Entity public class Branch implements Serializable { private static final long serialVersionUID...

how to fetch a column in browse_record_list in orm browse method in openERP

python-2.7,orm,openerp-7
I'm beginner in openERP. I'm trying to get a column in a table. While using ORM browse method and iterating that object i got the result in browse_record_list as browse_record(table.name,21). I want to fetch that particular id 21 alone through that browse method but instead im getting same browse_record as...

Ruby ActiveRecord: How to connect two rooms with an exit

ruby,activerecord,orm,rails-activerecord,adventure
I am making a small text-adventure, and I want to use ActiveRecord as Object Relational Mapping. What I'm having trouble with, is understanding how to connect two rooms together using an exit. The following facts are a given: A room can have multiple exits An exit can be in different...

How can I calculate Median, deriviation, variance etc using Arel in ROR?

ruby-on-rails,ruby,orm,arel
I have looked in Arel which is on top of ORM in ROR. Is it any library or another function of Arel which allows me to calculate median, deriviation, variance etc?...

How to use Phalcon ORM for deleting a result set

php,orm,phalcon,deletion
Consider the following code form document foreach (Robots::find("type='mechanical'") as $robot) { if ($robot->delete() == false) { echo "Sorry, we can't delete the robot right now: \n"; foreach ($robot->getMessages() as $message) { echo $message, "\n"; } } else { echo "The robot was deleted successfully!"; } } Using Phalcon, is it...

Infinite loop in Doctrine event listener when trying to save additional entity

php,symfony2,orm,doctrine2,doctrine
I want that every time a new Distance entity (from Place_A to Place_B) is saved, the reverse distance (from Place_B to Place_A) gets inserted too into the DB. My problem is the following listener loops infinitely (hence the counter): class Listener { public $count; public function prePersist(LifecycleEventArgs $eventArgs) { if...

Wrong datatype for referenced entity on Doctrine ObjectSelect

php,zend-framework,orm,doctrine2
I have a form which uses Doctrine's ObjectSelect to make a dropdown $this->add(array( 'name' => 'category', 'type' => 'DoctrineModule\Form\Element\ObjectSelect', 'options' => array( 'label' => 'Category', 'object_manager' => $em, 'target_class' => 'Blog\Entity\Category', 'property' => 'name' ), 'attributes' => array( 'required' => true ) )); the issue I have, is that this...

Play Ebean .orderBy() broken? Replacing character with “$ ”

java,sql,orm,playframework-2.3,ebean
The following Ebean find String join = "trackToArtists.artist.artistToTags.tag.stationToTags.station"; return find .where() .eq(join, station) .ge(join + ".energyMin", settings.energyMin) .le(join + ".energyMax", settings.energyMax) .ge(join + ".livenessMin", settings.livenessMin) .le(join + ".livenessMax", settings.livenessMax) .ge(join + ".tempoMin", settings.tempoMin) .le(join + ".tempoMax", settings.tempoMax) .ge(join + ".acousticnessMin", settings.acousticnessMin) .le(join + ".acousticnessMax", settings.acousticnessMax) .ge(join +...

django, one orm command execute duplicate sql sentence

mysql,django,orm
test code: 1、 b = 1 2、 aa = Forum.objects.values('id') 3、 d = 2 4、 print aa[0]['id'] then I monitor the mysql execute with linux command: tail -f /var/log/mysql/mysql.log then I debug the code line by line, at line 2 ,the monitor screen print 25 Query SELECT `forum`.`id` FROM `forum`...

In simple RESTful design, does PATCH imply mapping to CRUD's (ORM's) “update” and PUT to “destroy”+“create” (to replace a resource)?

database,rest,http,orm,crud
I'm trying to create a simple REST API and map it to CRUD. I have an ORM (DataMapper) which has methods like create, update and destroy. If I get it right, given a resource {a:'foo',b:'bar',c:'baz'}, performing a PUT {b:'qux'} is supposed to replace the resource and result in the same...

join and orwhere ends to AND

orm,cakephp-3.0
I have the follwing code: $_duplicates = $this->find() ->innerJoin( ['c' => 'contacts'], //alias [ 'Contacts.contactname != ' => '', 'Contacts.id < c.id', 'c.id > ' => 0 ] ) ->select(['Contacts.id', 'Contacts.contactname', 'Contacts.legalname', 'c.id', 'c.contactname', 'c.legalname']) ->orWhere([ 'LEVENSHTEIN(Contacts.contactname, c.contactname) <= ' => $distance, 'LEVENSHTEIN(Contacts.contactname, c.legalname) <= ' => $distance, 'LEVENSHTEIN(Contacts.legalname, c.contactname)...

Laravel - Eloquent “Has”, “With”, “WhereHas” - What do they mean?

laravel,orm,eloquent,relational-database,relationship
I've found the concept and meaning behind these methods to be a little confusing, is it possible for somebody to explain to me what the difference between has and with is, in the context of an example (if possible)?

Set database.yml using environment variables in Sinatra

mysql,ruby,orm,sinatra,sinatra-activerecord
I have a very weird requirement in a project I am working on. I have file stored in some location /etc/config/config.json which contains database information like Host, Port, Username or Passwordor roughly looks as below: { "mysql-db": { "host": "172.17.0.27", "port": 3306, "password": "root", "username": "root" } } I am...

How to speedup Hibernate DML statements for one-to-many associations

java,performance,hibernate,jpa,orm
I have been trying to optimize a hibernate application and one of the biggest problems I have faced with Hibernates efficiency is its tendency to execute n+1 queries for a simple crud operation with child entities. I have been able to prevent n+1 queries for select operations by using @Fetch(FetchMode.JOIN)...

dynamic search with django orm

python,django,orm,dynamicquery
Using django, I want to dynamically search for text across multiple fields. I have a list of fields to search across as well as the text to search against. I also have an initial queryset to query against. Something along these lines: def dynamic_search(queryset): search_fields = ["search_field1", "search_field2", "search_field3"] search_text...

Managing per form ObjectContext lifetime

c#,winforms,entity-framework,orm
For ORMs like EF and NHibernate, multiple places suggest using "context per method" (or per request, per transaction) for web apps and services and using "context per form" for thick clients like WinForms and WPF. In C#, resource disposal with context per method is clean and clear with a using...

Undestanding how to use JPA to abstract the ORM

java,spring,hibernate,jpa,orm
I am working on a Java project for the university and I am trying to learn about framework, technologies and best practices for creating a well structured software that follows software engineering principles. I decided to use Spring (Spring-data-jpa), and Hibernate for the standalone software and now I am having...

How to handle Propel environment variables

php,variables,orm,configuration,propel
I am trying to setup some configuration for unit-testing my application. Therefore I will need to setup different database connections. I have tried to follow the documentation (Environment Variables Doc) but I don't understand where to save the environment variables so they can be found when I have something like:...

How to select all rows that don't have one-to-many entity with certain value using Doctrine

php,mysql,orm,doctrine2,doctrine
I have two entities: Cage and Bird. Cage has Birds inside so their relationship is one-to-many. Bird has a field name. How can I select all Cages where there's no Bird with name eagle inside. I was trying to do this: $cages = $this->createQueryBuilder("c") ->leftJoin("c.birds", "b") ->where("b.name != :name") ->setParameter("name",...

Parameterize ORM query with where in clause

hibernate,orm,coldfusion
I'm trying to parametrize a query that is currently working and is ripe for an SQL injection attack: qryAwards = ORMExecuteQuery( "from Award where awardID in (#form.deleteAwardList#) and Game.Season.User.userID=:uid", {uid=session.userID} ); if(not isNull(qryAwards) and arrayLen(qryAwards)){ for(i in qryAwards){ entityDelete(i); } } I tried this, having the param without single quotes:...

How to save additional entity while persisting another in Doctrine?

symfony2,orm,doctrine2,doctrine
I've got a Place entity and a Distance one, like so: class Place { /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** @ORM\Column(type="string", length=62, nullable=false) */ private $name; /** @ORM\OneToMany(targetEntity="Distance", mappedBy="origin") */ protected $distancesTo; /** @ORM\OneToMany(targetEntity="Distance", mappedBy="destination") */ protected $distancesFrom; } class Distance { /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ private...

Hibernate @OneToMany tries to insert null

java,hibernate,jpa,orm,hibernate-mapping
I have the following simple example. When it runs, I see the QuoteRequest object being generated with auto-generated id. Next, I see the Accidents object being generated, but quote_request_id that's being inserted is null, so I get an error: Column 'quote_request_id' cannot be null @Entity @Table(name = "Quotes") public class...

When Should I Use @JoinColumn or @JoinTable?

java,hibernate,jpa,orm,hibernate-mapping
@JoinColumn gives an Entity a foreign key to another Entity whereas @JoinTable will list the relationship between all relationships between Entity A and Entity B. As far as I can tell, they both appear to do similar things. When should I use one or the other?

Filter by belongsToMany relation field

sql,node.js,orm,sequelize.js
It is impossible to filter data using a linked table. There are two tables Instructor and Club. They related how belongsToMany. I need to get all Instructors which club_id = value. Instructor model: sequelize.define('Instructor', { instance_id: DataTypes.INTEGER, name: DataTypes.STRING(255) }, { tableName: 'instructors', timestamps: false, classMethods: { associate: function (models)...

Removing related entity Symfony2

symfony2,orm,doctrine2
I have related entities. Many to Many relation and the annotation exists on only one entity: /** * @ORM\ManyToMany(targetEntity="Event") * @ORM\JoinTable(name="viewed_events", * joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")}, * inverseJoinColumns={@ORM\JoinColumn(name="event_id", referencedColumnName="id")} * ) **/ protected $viewedEvents; The problem is when I try to delete Event entity I get Integrity constraint violation: 1451 Cannot delete...

Blocking Updating or Inserting an Entity when using Cascade in Hibernate

java,hibernate,jpa,orm,hibernate-mapping
I have an entity , EntHesaplasma , this entity has a relationship with EntCariHareketler entity. I have a foreign key in the EntHesaplasma entity for EntCariHareketler. I want to set a relationship between them , but I dont want to update,insert or remove operations on EntCariHareketler entity. Only I want...

Which one should be preferred 1:1,0 or nullable fields on one table on relational database?

entity-framework,database-design,orm,ef-code-first,relational-database
I use Azure Sql and Entity-Framework Code First. I have Transaction Table. There are 4 types which are buy/sell, withdrawal, deposit and fee. For example, I need DepositCode for deposit transactions but this column will be null for others. Also I need ItemPrice and ItemAmount for buy/sell but it will...

Partner Ledger Report using ORM methods in Odoo8

python-2.7,orm,odoo-8
I am working on partner ledger report and i have prepared report using SQL query def lines(self, partner): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted'] full_account = [] if self.reconcil: RECONCILE_TAG = " " else: RECONCILE_TAG = "AND l.reconcile_id IS NULL" self.cr.execute( "SELECT l.id, l.date, j.code, acc.code...

Can a JPA entity have multiple OneToMany associations?

java,hibernate,jpa,orm,hibernate-mapping
Adding two OneToMany associations to my entity class seems not to work. It works fine if I remove one of them. @Entity @Table(name = "school") public class School { private List<Teacher> teachers; private List<Student> students; @OneToMany(cascade=CascadeType.ALL, mappedBy = "school", fetch = FetchType.EAGER) public List<Teacher> getTeachers() return this.teachers; } public void...

Correct usage of Session.persist()

java,hibernate,orm
I'm trying to understand the semantics of Session.persist(), and exactly what the entity manager does with unsaved transient instances. What I want to achieve is to just add a new transient instance to the session and have Hibernate execute an INSERT when the session is flushed. I have found that...

How to query in Doctrine2 WHERE = 'value from a related Entity'

php,json,symfony2,orm,doctrine2
The relationship is as easy as Many posts -> one User // Acme\AppBundle\Entity\UploadPlugin\Post /** * @ORM\ManyToOne(targetEntity="Acme\AppBundle\Entity\AuthBundle\LiveUser") * @ORM\JoinColumn(name="posts", referencedColumnName="id") **/ private $postOwner; So when I create a new Post like this : $image = new Post(); $image->setName($imagetitle); $image->setPostowner($this->getUser()); //(...) set further stuff $em = $this->getDoctrine()->getManager(); $em->persist($image); $em->flush(); I'd just return...

How to INSERT suing a SELECT in Hibernate

java,sql,hibernate,orm,hql
I need to implement the following request in hibernate: insert into my_table(....,max_column) values(...,(select max(id) from special_table where ....)) How to do that in hibernate, using annotations? special_table may be not a child or dependency of my_table, just a subselect. ...

Hibernate Storing Fields inside Classes

java,hibernate,orm,relational-database
I have two classes with two individual tables, "Employee" and "Company". I would like to keep a list of employee inside Company class. It is easy but I do not know how to represent this list in the database side. Class 'Company': @Entity @Table(name = "company") public class Company {...

how to remove association in sequelize without extra query?

mysql,node.js,orm,sequelize.js
I have many to many association between exercise and muscle models. I remove single association models.Exercise.find({where: {id: exerciseId}}) .then(function(exercise){ exercise.removeMuscle(muscleId); res.sendStatus(200); }); ORM runs 3 queries and 2 of them are similar Executing (default): SELECT `Muscule`.`id`, `Muscule`.`title`, `Muscule`.`description`, `Muscule`.`video`, `Muscule`.`createdAt`, `Muscule`.`updatedAt`, `muscle_exercise`.`createdAt` AS `muscle_exercise.createdAt`, `muscle_exercise`.`updatedAt` AS `muscle_...

Persisting multiple associations to same entity in Hibernate

java,hibernate,jpa,orm
I am making a chat system, and I have the below database schema (everything not related to the core problem has been removed). A thread represents a conversation between two participants. When a new thread is created (persisted), two participants should be created; one for the sender and one for...

ORM/Doctrine2 - When to persist?

php,orm,doctrine2
This has been bugging me for a while. In Doctrine2, we have the: ObjectManager function: void persist(object $object = null) You only need to call it on new entities. My question though, is "when" should it be called? Immediately after creating the entity, or immediately before flushing it? I can't...

Is there a detailed comparison between Propel 2 and Doctrine 2

performance,orm,doctrine,comparison,propel
From the existing comparisons between 1.x versions of Propel and Doctrine, I couldn't decide whether to use Doctrine 2.x or Propel 2.x for my new project. I have some experience with Propel but am not happy with the way Propel 2 broke compatibility with previous versions. Hence this question. Is...

Doctrine include null on join

sql,symfony2,orm,doctrine2
I am trying to create a query that will fetch every users, and, for those that have received a feedback, fetch their rating average as well. After some research, I have crafted a query that will return all the users that have received a feedback and their respective rating. Which...

cakephp 2.x using 'NOT IN' in subquery

mysql,cakephp,orm
I have this tiny mysql query(it returns element which dont have 1,3,5 state): SELECT DISTINCT number FROM records WHERE number NOT IN ( SELECT number FROM records WHERE state_id = 1 or state_id = 3 or state_id = 5) In cakephp i am not good at subquery but i was...

Create Postgres database on the fly, if it doesn't exists using Hibernate

java,database,hibernate,postgresql,orm
Using H2, Environment.HBM2DDL_AUTO, "create" creates the database if it does not exist yet. However, in Postgres, the non existing DB is not created and thus an exception which says something like "DB does not exist" is thrown. Is there a way to configure Postgres to create a non existing database...

Hibernate does't update joined collection

hibernate,orm
I have an Employee entity (employee(id,name,company_id)): @Entity public class Employee { @Id @Column(name="ID") private Integer id; @ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL) @JoinColumn(name = "COMPANY_ID") private Company company; ... } and I have a Company entity (company(id,name)): @Entity public class Company { @Id @Column(name="ID") private Integer id; @OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL) @JoinColumn(name="COMPANY_ID") @Where(clause="status_code =...

The file could not be found while using LifecycleCallbacks

php,symfony2,orm,doctrine,assert
I have problem with form validation in symfony2. In my case the $form->isValid() command results in The file could not be found. even though that I provide a file during filling in the form Additionally debuging of setFile function in documents entity leads to conclusion that file value is set...

Python SQLAlchemy - ForeignKey error

python,mysql,orm,sqlalchemy,foreign-keys
I'm trying to learn Python ORM using SQLAlchemy. I have these MySQL tables: CREATE TABLE address ( id INT NOT NULL AUTO_INCREMENT, street VARCHAR(45) NOT NULL, city VARCHAR(45) NOT NULL, PRIMARY KEY (id)) ENGINE = InnoDB; CREATE TABLE user ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(45) NOT NULL, email...

Django ORM save multiple forms at once

python,django,forms,orm
I have a question about saving three forms at once. First two forms save OK with no problems, but third form must request id from form2 when form2 is saved to database. Don't know where is problem on this procedure and where I make mistake. models.py class Product_service(models.Model): id =...

HibernateException: Illegal attempt to associate a collection with two open sessions

hibernate,session,orm,sql-delete
Here is my tables: Orders.java @Entity public class Orders implements Serializable { @Id @GeneratedValue private Integer id; @Column(nullable = false) private Date orderDate; @ManyToOne(cascade = CascadeType.ALL) private User user; @OneToMany(mappedBy = "orders", cascade = CascadeType.ALL) private Set<OrderItem> orderItems = new HashSet<OrderItem>(); //getter/setters I am going to delete one record from...

Sequelize.js - how to properly use get methods from associations (no sql query on each call)?

node.js,orm,sequelize.js
I'm using Sequelize.js for ORM and have a few associations (which actually doesn't matter now). My models get get and set methods from those associations. Like this (from docs): var User = sequelize.define('User', {/* ... */}) var Project = sequelize.define('Project', {/* ... */}) // One-way associations Project.hasOne(User) /* ... Furthermore,...

Error No : 150 in creating table via hibernate

java,hibernate,orm,hibernate-mapping
I am creating table one to many mapping via hibernate but some problem occur it could not update table. StackTrace May 05, 2015 8:36:45 PM org.hibernate.cfg.Configuration configure INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml May 05, 2015 8:36:45 PM org.hibernate.cfg.Configuration getConfigurationInputStream INFO: HHH000040: Configuration resource: /hibernate.cfg.xml May 05, 2015 8:36:45 PM...

How do I create a complex left outer join in Yii2?

php,activerecord,orm,yii2
How do I perform this query in Yii2? SELECT `keyword`.`id`, `keyword`, `volume`, `cpc`, `competition`, `keyword_id` FROM `keyword` LEFT JOIN `ad_group_keyword` ON keyword.id = ad_group_keyword.keyword_id and ad_group_id = 1 WHERE ((`keyword_id` IS NULL) AND (NOT (`volume` IS NULL))) AND (NOT (`cpc` IS NULL)) ORDER BY volume desc LIMIT 1; I tried...

Select count with “where” using CriteriaBuilder

hibernate,jpa,orm
I'm trying to make something like this SELECT COUNT(*) FROM Tickets WHERE ticketStatus = 3 AND ... but only using CriteriaBuilder provided by JPA. Here's what I've got: private class Criteria { CriteriaBuilder builder; CriteriaQuery<TicketModel> query; Root<TicketModel> root; public Criteria() { builder = em.getCriteriaBuilder(); query = builder.createQuery(TicketModel.class); root = query.from(TicketModel.class);...

how to convert join in my sql query to laravel ORM

php,mysql,laravel,orm,laravel-5
I'm new in laravel 5 how can i convert this query to laravel ORM select `users`.`id`, `users`.`username`, count(`ord`.`id`) As total FROM `users` LEFT JOIN `orders` AS `ord` ON `ord`.`empolyee_id` = `users`.`id` AND DATE(`ord`.`created_at`) = $date GROUP BY `users`.`id` I tried this solution but it didn't work correctly $orders = Order::rightjoin('users',function($join)...

Specifying a primary key on @ElementCollection

java,hibernate,jpa,orm,hibernate-mapping
So, there is that behavior with innodb that can cause problem if some tables lack of primary key. So with Hibernate, I am looking for a key to specifies a primary key on a @ElementCollection table with a Set as the underling data structure. I found a way to have...

How to set the previous Parent id on a Child column with Hibernate

java,sql,database,hibernate,orm
I have parent and child entities: @Entity public class Parent{ @Id private Long id; @ManyToOne private Child child; ..... } @Entity public class Child{ @Id private Long id; public List<Parent> all parents; **public Long lastParentId;** ..... } The issue is I need to update lastParentId in child every time I...

All data in a table with relationships, empty arrays

php,laravel,laravel-4,orm,model
I have the Post, Category and Tag models with their relationships and working well in other inquiries. If I get the categories and tags of a post specifically, the data returns correctly me. $post = Post::with('categorias', 'etiquetas')->find($id)->toArray(); With Post::has only shows data Posts that do have categories, at least I...

Why is Yii2's ActiveRecord using lots of single SELECTs instead of JOINs?

php,mysql,activerecord,orm,yii2
I'm using Yii2's ActiveRecord implementation in (hopefully) exactly the way it should be used, according to the docs. Problem In a quite simple setup with simple relations betweens the tables, fetching 10 results is fast, 100 is slow. 1000 is impossible. The database is extremely small and indexed perfectly. The...

How to Map a Ternary Map of Dates With a Bidirectional Relationship?

java,database,hibernate,collections,orm
I've read: JPA: How to map a Map with Date as key but I have the opposite of the question, I have the value component of the Map as a Date. How should I map this? Map: Map<Club, java.util.Date> Can you show an example including the code for the Club...

How to easily use and access meta attributes in Eloquent - Laravel

laravel,orm,eloquent
I have a 'contents' table like this : id title description I have another 'meta' table that stores extra fields for my contents : id content_id field_name field_vaue My question is How can I access MyModel->field_name as if it is in contents table I know I can use hasMany relation...

Play Framework 2.x Ebean query ManyToMany for all

java,orm,playframework-2.0,ebean
I have two models in Play Framework 2/Ebean, 'Article' and 'Tag', which has a ManyToMany-relationship to each other. Article: @Entity public class Article extends Model { @ManyToMany List<Tag> tags; // ... } Tag: @Entity public class Tag extends Model { @ManyToMany List<Article> articles; // ... } Given a List<Tag>, how...

Querying one-to-one in laravel

php,laravel-4,orm,eloquent
I have two models city and business.I have to perform below queries Find Business by city name. Find Top 10 cities which have the maximum business. Here is the models Business class Business extends \Eloquent { protected $fillable = [ 'business_type', 'first_name', 'last_name', 'email', 'password', 'designation_id', 'name', 'description', 'portfolio_id', 'image',...

Django Query to get customer_name who has used a particular keyword maximum no. of times in feedback?

python,django,database,orm
I have these models: class Customer(models.Model): customer_name = models.CharField(max_length=100) def __unicode__(self): return self.customer_name class Feedback(models.Model): customer_name = models.ForeignKey(Customer) feedback_string = models.CharField(max_length=100) def __unicode__(self): return self.feedback_string I want to get the name of customer who has used a particular keyword(for example: "good") maximum times in his/her all the feedbacks. (each feedback...

Correct form to get last uer id in laravel5

php,orm,user,eloquent
Good Morning ! I am developing a profile user and I have the following doubt. I know that I get my last user which the following form $full = User::orderBy('id','desc')->take(1)->get(); I recieve this json with this eloquent. . [{"id":58,"nif":"AAAA","name":"AAA","cognoms":"AAA","file":"uploads\/\/f0414.gif","birthday":"0000-00-00","presentacion":"descripciones","email":"[email protected]","idempresa":1,"id_poblacion":2254,"id_online":0,"created_at":"2015-05-24 00:00:40","updated_at":"2015-05-24 00:00:40"}] But...

Laravel Eloquent Relationship Through Another Table

laravel,laravel-4,orm,eloquent,laravel-5
I have the following database tables: Seasons id number Teams id name Standings id season_id team_id The question is, how could I get all of the teams in a season through the standings table. At the moment I am getting all of the teams this way: $teams = []; $standings...

DDD logic and Persistence Ignorance

c#,.net,orm,domain-driven-design,persistence
Consider the following scenario: public class Document { private ISet<User> sharedWith; public Document(string name) { this.sharedWith = new HashSet<User>(); this.Name = name; } public string Name { get; private set; } public IEnumerable<User> SharedWith { get { return this.sharedWith; } } public void ShareWith(User user) { if (this.SharedWith.Contains(user)) { throw...

Get primary key of Eloquent model instance

php,mysql,laravel,orm,eloquent
I'm happy enough to work on a project with (not) very consistent column names in our MySQL database. We have camelCase, PascalCase, 'Id', ID and it's driving me nuts. I've decided to start using Eloquent in our application (which is NOT Laravel). I would love to have a method of...

Outer right join doesn't work in NHibernate

mysql,nhibernate,orm,fluent-nhibernate,hql
So I'm having two tables: Table 1: Item id : int title : varchar comments : varchar Table 2: Rating id : int isUpvote : bit date : datetime item_id : int One Item can have several ratings. IsUpvote states whether a Rating is a like or dislike. I'm using...

Propel ORM left join select

mysql,join,orm,propel
I have 3 table major table: +----+------------+ | id | major | +----+------------+ | 1 | Computer | | 2 | Architect | | 3 | Designer | +----+------------+ classroom table: +----+----------+-------+ | id | major_id | name | +----+----------+-------+ | 1 | 1 | A | | 2 |...

Fetch a Model's associations in Laravel to simplify creation/update

php,laravel,orm,sync
I have a Movie model with the following associations (belongsToMany): Actor Country Genre ... When a form is posted, I have this data (skipping a lot of details here): 'actors' => array( 'Cary Grant', 'Grace Kelly', ... ), 'genres' => array( 'Drama', ... ), ... I'd like my update()/store() controller...

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; /** * *...

Right way to handle database access in PHP OOP

php,database,oop,pdo,orm
I need some help with database access in PHP. I'm trying to do things the OOP way but I'm not sure if I'm heading the right way. Lets say I have a class Person, for example: class Person { private $id; private $firstname; private $lastname; // maybe some more member...