Search Results

Search found 2412 results on 97 pages for 'relationship'.

Page 16/97 | < Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >

  • inheriting scope from a has_many relationship

    - by hb922
    I am using ruby on rails 3.1 and have 2 models, an event and a group. Each event has_many groups, but has to have at least one "master" group, where the column :is_master = true Class Group < ActiveRecord::Base has_many :users belongs_to :event scope :master, where (:is_master => true) end Class Event< ActiveRecord::Base has_many :groups def master_group groups.master end end I want to be able to default all properties of the master group to the event, so for example, event.users.count should be the same as event.master_group.users.count. Is there any way to do something like this? Can I do a has_many :through = master_group? Am I approaching this the wrong way? Thanks!

    Read the article

  • Cakephp: Extend search capability to hasMany Relationship

    - by Chris
    I have two models: Car hasMany Passengers Passenger belongsTo Car I want to implement a search using Cake Search. The user should input a number and the searchengine should return all cars that have less than this number passengers. In my search form: echo $form->input('passengers', array('label' => 'Passengers', 'div' => false)); In my Car model: public $filterArgs = array( array('name' => 'passengers', 'type' => 'int'), ); In the controller: public $presetVars = array( array('field' => 'passengers', 'type' => 'int') } I thought of adding a function to the model that returns the number of passengers: function countPassengers(){ return(count($this->Car->Passenger)); //Not sure if this works } And how to I implement this search criteria?: return all Cars where countPassengers()<passenger

    Read the article

  • Hibernate mapping to manage bidirectional relationship using intermediate table

    - by shikarishambu
    I have an object hierarchy that is as follows. Party inherited by Organization and Person Organization inherited by Customer, Vendor Person inherited by Contact In the database I have the following tables Party, Customer, Vendor, Contact. All of them have a corresponding row in Party table. Contact belongs to either Vendor or Customer. I have a field on the Contact table for org_party_id. However, since the organization can be either a Customer or Vendor I need to be able to look at different tables. Is there a way to map this in hibernate? Or, a better way to manage it in DB/ hibernate?

    Read the article

  • JDO architecture: One to many relationship and cascading deleting

    - by user361897
    I’m new to object oriented database designs and I’m trying to understand how I should be structuring my classes in JDO for google app engine, particularly one to many relationships. Let’s say I’m building a structure for a department store where there are many departments, and each department has many products. So I’d want to have a class called Department, with a variable that is a list of a Product class. @PersistenceCapable public class Department { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private String deptID; @Persistent private String departmentName; @Persistent private List<Product>; } @PersistenceCapable public class Product { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private String productID; @Persistent private String productName; } But one Product can be in more than one Department (like a battery could be in electronics and household supplies). So the next question is, how do I not duplicate data in the OOD world and have only one copy of product data in numerous departments? And the next question is, let’s say I delete out a particular product, how do each of the departments know it was deleted?

    Read the article

  • Do I need to manually create indexes for a DBIx::Class belongs_to relationship

    - by Dancrumb
    I'm using the DBIx::Class modules for an ORM approach to an application I have. I'm having some problems with my relationships. I have the following package MySchema::Result::ClusterIP; use strict; use warnings; use base qw/DBIx::Class::Core/; our $VERSION = '1.0'; __PACKAGE__->load_components(qw/InflateColumn::Object::Enum Core/); __PACKAGE__->table('cluster_ip'); __PACKAGE__->add_columns( # Columns here ); __PACKAGE__->set_primary_key('objkey'); __PACKAGE__->belongs_to( 'configuration' => 'MySchema::Result::Configuration', 'config_key'); __PACKAGE__->belongs_to( 'cluster' => 'MySchema::Result::Cluster', { 'foreign.config_key' => 'self.config_key', 'foreign.id' => 'self.cluster_id' } ); As well as package MySchema::Result::Cluster; use strict; use warnings; use base qw/DBIx::Class::Core/; our $VERSION = '1.0'; __PACKAGE__->load_components(qw/InflateColumn::Object::Enum Core/); __PACKAGE__->table('cluster'); __PACKAGE__->add_columns( # Columns here ); __PACKAGE__->set_primary_key('objkey'); __PACKAGE__->belongs_to( 'configuration' => 'MySchema::Result::Configuration', 'config_key'); __PACKAGE__->has_many('cluster_ip' => 'MySchema::Result::ClusterIP', { 'foreign.config_key' => 'self.config_key', 'foreign.cluster_id' => 'self.id' }); There are a couple of other modules, but I don't believe that they are relevant. When I attempt to deploy this schema, I get the following error: DBIx::Class::Schema::deploy(): DBI Exception: DBD::mysql::db do failed: Can't create table 'test.cluster_ip' (errno: 150) [ for Statement "CREATE TABLE `cluster_ip` ( `objkey` smallint(5) unsigned NOT NULL auto_increment, `config_key` smallint(5) unsigned NOT NULL, `cluster_id` char(16) NOT NULL, INDEX `cluster_ip_idx_config_key_cluster_id` (`config_key`, `cluster_id`), INDEX `cluster_ip_idx_config_key` (`config_key`), PRIMARY KEY (`objkey`), CONSTRAINT `cluster_ip_fk_config_key_cluster_id` FOREIGN KEY (`config_key`, `cluster_id`) REFERENCES `cluster` (`config_key`, `id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `cluster_ip_fk_config_key` FOREIGN KEY (`config_key`) REFERENCES `configuration` (`config_key`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB"] at test_deploy.pl line 18 (running "CREATE TABLE `cluster_ip` ( `objkey` smallint(5) unsigned NOT NULL auto_increment, `config_key` smallint(5) unsigned NOT NULL, `cluster_id` char(16) NOT NULL, INDEX `cluster_ip_idx_config_key_cluster_id` (`config_key`, `cluster_id`), INDEX `cluster_ip_idx_config_key` (`config_key`), PRIMARY KEY (`objkey`), CONSTRAINT `cluster_ip_fk_config_key_cluster_id` FOREIGN KEY (`config_key`, `cluster_id`) REFERENC ES `cluster` (`config_key`, `id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `cluster_ip_fk_config_key` FOREIGN KEY (`config_key`) REFERENCES `configuration` (`conf ig_key`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB") at test_deploy.pl line 18 From what I can tell, MySQL is complaining about the FOREIGN KEY constraint, in particular, the REFERENCE to (config_key, id) in the cluster table. From my reading of the MySQL documentation, this seems like a reasonable complaint, especially in regards to the third bullet point on this doc page. Here's my question. Am I missing something in the DBIx::Class module? I realize that I could explicitly create the necessary index to match up with this foreign key constraint, but that seems to be repetitive work. Is there something I should be doing to make this occur implicitly?

    Read the article

  • jpa relationship-Google app engine

    - by megala
    I created two tables in google appengine datastore using JPA. Table1: *groupname pk *groupid *groupdesc *emailper Table2: *groupname *memberid *membername My constraint is if i enter data into table2 it check whether group already exists or not in table.If exists than only it store the data into table .How to solve this?

    Read the article

  • SQL Server 2008: The columns in table do not match an existing primary key or unique constraint

    - by 109221793
    Hi guys, I need to make some changes to a SQL Server 2008 database. This requires the creation of a new table, and inserting a foreign key in the new table that references the Primary key of an already existing table. So I want to set up a relationship between my new tblTwo, which references the primary key of tblOne. However when I tried to do this (through SQL Server Management Studio) I got the following error: The columns in table 'tblOne' do not match an existing primary key or UNIQUE constraint I'm not really sure what this means, and I was wondering if there was any way around it?

    Read the article

  • Defining relationship in value objects using Hibernate

    - by kate
    Hi, We have three tables .We need to get data from these tables based upon particular conditions. Like if TableA.columv=TableB.columc=tableC.column then get data. We are using value objects to map Objects to relations. Question is how to maintain these relation ships in value objects. And how to retrieve data from it. We have one value object per table.

    Read the article

  • Flash relationship map

    - by John
    Hi, Does anyone know any Flash fla's which are out there and free which do something similar to http://audiomap.tuneglue.net/ (you have to type in a search term to see it in action). What I'm after is the flash to create the node in the middle which expands out into children and then each of those children can be expanded out into more children, etc. while keeping their distance from one another so as to not overlap. I'd like it so that if you clicked on a node to expand it, it would shoot off to a web site and get an xml feed which could then be used to create the children. Thanks

    Read the article

  • multiple-to-one relationship mysql, submissions

    - by Yulia
    Hello, I have the following problem. Basically I have a form with an option to submit up to 3 images. Right now, after each submission it creates 3 records for album table and 3 records for images. I need it to be one record for album and 3 for images, plus to link images to the album. I hope it all makes sense... Here is my structure. TABLE `albums` ( `id` int(11) NOT NULL auto_increment, `title` varchar(50) NOT NULL, `fullname` varchar(40) NOT NULL, `email` varchar(100) NOT NULL, `created_at` datetime NOT NULL, `theme_id` int(11) NOT NULL, `description` int(11) NOT NULL, `vote_cache` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=20 ; TABLE `images` ( `id` int(11) NOT NULL auto_increment, `album_id` int(11) NOT NULL, `name` varchar(30) NOT NULL, and my code function create_album($params) { db_connect(); $query = sprintf("INSERT INTO albums set albums.title = '%s', albums.email = '%s', albums.discuss_url = '%s', albums.theme_id = '%s', albums.fullname = '%s', albums.description = '%s', created_at = NOW()", mysql_real_escape_string($params['title']), mysql_real_escape_string($params['email']), mysql_real_escape_string($params['theme_id']), mysql_real_escape_string($params['fullname']), mysql_real_escape_string($params['description']) ); $result = mysql_query($query); if(!$result) { return false; } $album_id = mysql_insert_id(); return $album_id; } if(!is_uploaded_file($_FILES['userfile']['tmp_name'][$i])) { $warning = 'No file uploaded'; } elseif is_valid_file_size($_FILES['userfile']['size'][$i])) { $_POST['album']['theme_id'] = $theme['id']; create_album($_POST['album']); mysql_query("INSERT INTO images(name) VALUES('$newName')"); copy($_FILES['userfile']['tmp_name'][$i], './photos/'.$original_dir.'/' .$newName.'.jpg');

    Read the article

  • Insert Into Two SQL Tables From XML Maintaining Relationship

    - by Thx
    I am looking to insert records from xml into two different tables. For example <Root> <A> <AValue>1</AValue> <Children> <B> <BValue>2</BValue> </B> </Children> </A> </Root> Would insert a record into table A AID AValue # 1 also insert a record into table B BID AID BValue # #(Same as AID Above) 2 I have this DECLARE @idoc INT DECLARE @doc NVARCHAR(MAX) SET @doc = ' <Root> <A> <AValue>1</AValue> <Children> <B> <BValue>2</BValue> </B> </Children> </A> </Root> ' EXEC sp_xml_preparedocument @idoc OUTPUT, @doc CREATE TABLE #A ( AID INT IDENTITY(1, 1) , AValue INT ) INSERT INTO #A SELECT * FROM OPENXML (@idoc, '/Root/A',2) WITH (AValue INT ) CREATE TABLE #B ( BID INT IDENTITY(1, 1) , AID INT , BValue INT ) INSERT INTO #B SELECT * FROM OPENXML (@idoc, '/Root/A/Children/B',2) WITH ( AID INT, BValue INT ) SELECT * FROM #A SELECT * FROM #B DROP TABLE #A DROP TABLE #B Thanks!

    Read the article

  • How to relate keywords to records - Many to Many

    - by webworm
    Hi All, I am looking for suggestions on database design for a sample jobs listing application. I have many jobs that I would like to associate various keywords with. Each job can have multiple keywords. I would like to store the keywords in a seperate table instead of in a field within the Job table so as to avoid mispellings in keywords. What is the best way to relate keywords to the jobs? I was thinking of using an intermediary table that would have a many to many relationship linking keywords to jobs. Is this the best way to go or should I just have a field in the Job table that contains multiple keywords? Thanks for any suggestions.

    Read the article

  • Core Data not-reverse relationship subquery

    - by user561485
    Hi, I have the following entities in CoreData: Village - villageID Bookmark - (relation) village There are multiple villages with each an unique villageID. I have a entity Bookmark which only has a relation to a Village entity; it isn't possible to make a reverse relation. Now I would like to get the village entities where there exists a Bookmark relation. I've red something about subqueries, but I can't get it right for this situation. It must be something like: Village.villageID IN (Bookmark.village.villageID) It isn't possible to get first all the Bookmarks and then loop to get all the Villages, because of the design of the framework. Can this be done in CoreData (I presume the answer is "Yes, of course!") and how?

    Read the article

  • Yii Many_Many Relationship and Form

    - by Thorpe Obazee
    // Post model return array( 'categories' => array(self::HAS_MANY, 'Category', 'posts_categories(post_id, category_id)') ); I already have the setup of tables posts id, title, content categories id, name posts_categories post_id, category_i The problem I have is that I am getting an error when creating this form: <?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'post-form', 'enableAjaxValidation'=>false, )); ?> <p class="note">Fields with <span class="required">*</span> are required.</p> <?php echo $form->errorSummary($model); ?> <div class="row"> <?php echo $form->labelEx($model,'title'); ?> <?php echo $form->textField($model,'title',array('size'=>60,'maxlength'=>255)); ?> <?php echo $form->error($model,'title'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'uri'); ?> <?php echo $form->textField($model,'uri',array('size'=>60,'maxlength'=>255)); ?> <?php echo $form->error($model,'uri'); ?> </div> <div class="row"> <?php echo $form->labelEx($model,'content'); ?> <?php echo $form->textArea($model,'content',array('rows'=>6, 'cols'=>50)); ?> <?php echo $form->error($model,'content'); ?> </div> <div class="row"> <?php // echo $form->labelEx($model,'content'); ?> <?php echo CHtml::activeDropDownList($model,'category_id', CHtml::listData(Category::model()->findAll(), 'id', 'name')); ?> <?php // echo $form->error($model,'content'); ?> </div> <div class="row buttons"> <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?> </div> <?php $this->endWidget(); ?> The error is: Property "Post.category_id" is not defined. I am quite confused. What should I be doing to correct this?

    Read the article

  • Rails: bi-directional has_many :through relationship

    - by Chris
    I have three models in a Rails application: Game represents an instance of a game being played. Player represents an instance of a participant in a game. User represents a registered person who can participate in games. Each Game can have many Players, and each User can have many Players (a single person can participate in multiple games at once); but each Player is in precisely one Game, and represents precisely one User. Hence, my relationships are as follows at present. class Game has_many :players end class User has_many :players end class Player belongs_to :game belongs_to :user end ... where naturally the players table has game_id and user_id columns, but games and users have no foreign keys. I would also like to represent the fact that each Game has many Users playing in it; and each User has many Games in which they are playing. How do I do this? Is it enough to add class Game has_many :users, :through => :players end class User has_many :games, :through => :players end

    Read the article

  • Entity Framework - Store parent reference on child relationship (one -> many)

    - by contactmatt
    I have a setup like this: [Table("tablename...")] public class Branch { public Branch() { Users = new List<User>(); } [Key] public int Id { get; set; } public string Name { get; set; } public List<User> Users { get; set; } } [Table("tablename...")] public class User { [Key] public int Id {get; set; } public string Username { get; set; } public string Password { get; set; } [ForeignKey("ParentBranch")] public int? ParentBranchId { get; set; } // Is this possible? public Branch ParentBranch { get; set; } // ??? } Is it possible for the User to know what parent branch it belongs to? The code above is not working. Entity Framework version 5.0 .NET 4.0 c#

    Read the article

  • Audit many-to-many relationship in NHibernate

    - by Kendrick
    I have implemented listeners to audit changes to tables in my application using IPreUpdateEventListener and IPreInsertEventListener and everything works except for my many-to-many relationships that don't have additional data in the joining table (i.e. I don't have a POCO for the joining table). Each auditable object implements an IAuditable interface, so the event listener checks to see if a POCO is of type IAuditable, and if it is it records any changes to the object. Look up tables implement an IAuditableProperty inteface, so if a property of the IAuditable POCO is pointing to a lookup table, the changes are recorded in the log for the main POCO. So, the question is, how should I determine I'm working with a many-to-many collection and record the changes in my audit table? //first two checks for LastUpdated and LastUpdatedBy ommitted for brevity else if (newState[i] is IAuditable) { //Do nothing, these will record themselves separately } else if (!(newState[i] is IAuditableProperty) && (newState[i] is IList<object> || newState[i] is ISet)) { //Do nothing, this is a collection and individual items will update themselves if they are auditable //I believe this is where my many-to-many values are being lost } else if (!isUpdateEvent || !Equals(oldState[i], newState[i]))//Record only modified fields when updating { changes.Append(preDatabaseEvent.Persister.PropertyNames[i]) .Append(": "); if (newState[i] is IAuditableProperty) { //Record changes to values in lookup tables if (isUpdateEvent) { changes.Append(((IAuditableProperty)oldState[i]).AuditPropertyValue) .Append(" => "); } changes.Append(((IAuditableProperty)newState[i]).AuditPropertyValue); } else { //Record changes for primitive values if(isUpdateEvent) { changes.Append(oldState[i]) .Append(" => "); } changes.Append(newState[i]); } changes.AppendLine(); }

    Read the article

  • Entity framework Update fails when object is linked to a missing child

    - by McKay
    I’m having trouble updating an objects child when the object has a reference to a nonexising child record. eg. Tables Car and CarColor have a relationship. Car.CarColorId CarColor.CarColorId If I load the car with its color record like so this var result = from x in database.Car.Include("CarColor") where x.CarId = 5 select x; I'll get back the Car object and it’s Color object. Now suppose that some time ago a CarColor had been deleted but the Car record in question still contains the CarColorId value. So when I run the query the Color object is null because the CarColor record didn’t exist. My problem here is that when I attach another Color object that does exist I get a Store update, insert error when saving. Car.Color = newColor Database.SaveChanges(); It’s like the context is trying to delete the nonexisting color. How can I get around this?

    Read the article

  • How to insert rows in a many-to-many relationship

    - by GSound
    Hello, I am having an issue trying to save into an intermediate table. I am new on Rails and I have spent a couple of hours on this but can't make it work, maybe I am doing wrong the whole thing. Any help will be appreciated. =) The app is a simple book store, where a logged-in user picks books and then create an order. This error is displayed: NameError in OrderController#create uninitialized constant Order::Orderlist These are my models: class Book < ActiveRecord::Base has_many :orderlists has_many :orders, :through => :orderlists end class Order < ActiveRecord::Base belongs_to :user has_many :orderlists has_many :books, :through => :orderlists end class OrderList < ActiveRecord::Base belongs_to :book belongs_to :order end This is my Order controller: class OrderController < ApplicationController def add if session[:user] book = Book.find(:first, :conditions => ["id = #{params[:id]}"]) if book session[:list].push(book) end redirect_to :controller => "book" else redirect_to :controller => "user" end end def create if session[:user] @order = Order.new if @order.save session[:list].each do |b| @order.orderlists.create(:book => b) # <-- here is my prob I cant make it work end end end redirect_to :controller => "book" end end Thnx in advance! Manuel

    Read the article

  • Core Data to-many relationship in code

    - by Jan Bezemer
    I have three entities: Session, User and Test. A session has 0-many users and a user can perform 0-6 tests. (I say 0 but in the real application always at least 1 is required, at least 1 user for a session and at least 1 test for a user. But I say 0 to express an empty start.) All entities have their own specific data attributes too. A user has a name, A session has a name, a test has six values to be filled in by the user, and so on. But my issue is with the relationships. How do I set multiple users and have them added to one session (same goes for multiple tests for one user). How do I show the content in a right way? How do I show a session that has multiple users and these users having completed multiple tests? Here's my code so far with regard to issue 1: Session *session = [NSEntityDescription insertNewObjectForEntityForName:@"Session" inManagedObjectContext:context]; session.name = @"Session 1"; User *users = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:context]; users.age = [NSNumber numberWithInt:28]; users.session = session; //sessie.users = users; [sessie addUserObject:users]; With regard to issue 2: I can log the session, but I can't get the user(s) logged from a session. NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Session" inManagedObjectContext:context]; [fetchRequest setEntity:entity]; NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error]; for (Session *info in fetchedObjects) { NSLog(@"Name: %@", info.name); NSLog(@"Having problems with this: %@",info.user); //User *details = info.user; //NSLog(@"User: %@", details.age); }

    Read the article

  • Hibernate many-to-many relationship

    - by Capitan
    I have two mapped types, related many-to-many. @Entity @Table(name = "students") public class Student{ ... @ManyToMany(fetch = FetchType.EAGER) @JoinTable( name = "students2courses", joinColumns = { @JoinColumn( name = "student_id", referencedColumnName = "_id") }, inverseJoinColumns = { @JoinColumn( name = "course_id", referencedColumnName = "_id") }) public Set<Course> getCourses() { return courses; } public void setCourses(Set<Course> courses) { this.courses = courses; } ... } __ @Entity @Table(name = "courses") public class Course{ ... @ManyToMany(fetch = FetchType.EAGER, mappedBy = "courses") public Set<Student> getStudents() { return students; } public void setStudents(Set<Student> students) { this.students = students; } ... } But if I update/delete Course entity, records are not created/deleted in table students2courses. (with Student entity updating/deleting goes as expected) I wrote abstract class HibObject public abstract class HibObject { public String getRemoveMTMQuery() { return null; } } which is inherited by Student and Course. In DAO I added this code (for delete() method): String query = obj.getRemoveMTMQuery(); if (query != null) { session.createSQLQuery(query).executeUpdate(); } and I ovrerided method getRemoveMTMQuery() for Course @Override @Transient public String getRemoveMTMQuery() { return "delete from students2courses where course_id = " + id + ";"; } Now it works but I think it's a bad code. Is there a best way to solve this problem?

    Read the article

< Previous Page | 12 13 14 15 16 17 18 19 20 21 22 23  | Next Page >