Search Results

Search found 23 results on 1 pages for 'hasone'.

Page 1/1 | 1 

  • cakePHP, multiple hasOne in a single model

    - by jason
    say you have 3 models : user, hair_color, and eye_color user hasOne hair_color user also hasOne eye_color however var $hasOne = 'hair_color'; var $hasOne = 'eye_color'; obviously wont work. So how do you implement many hasOne relationships in a single model? I assume the answer is in the cookbook, Im going over that area now, I suspect it has something to do with passing an array to $hasOne, but no example of doing this.

    Read the article

  • How to get HABTM associated data using hasOne binding

    - by Moin
    Hi, I am following example documented at http://book.cakephp.org/view/83/hasAndBelongsToMany-HABTM I am trying to retrieve associated data using hasOne. I created 3 tables posts, tags and posts_tags. I wrote following code to debug Posts. $this->Post->bindModel(array( 'hasOne' => array( 'PostsTag', 'FilterTag' => array( 'className' => 'Tag', 'foreignKey' => false, 'conditions' => array('FilterTag.id = PostsTag.tag_id') )))); $output=$this->Post->find('all', array( 'fields' => array('Post.*') )); debug($output); I was expecting output something like below. Array ( 0 => Array { [Post] => Array ( [id] => 1 [title] => test post 1 ) [Tag] => Array ( [0] => Array ( [id] => 1 [name] => php ) [1] => Array ( [id] => 2 [name] => javascript ) [2] => Array ( [id] => 3 [name] => xml ) ) } But my output do not have Tags at all. Here is what I got. Array ( [0] => Array ( [Post] => Array ( [id] => 1 [title] => test post1 ) ) [1] => Array ( [Post] => Array ( [id] => 2 [title] => test post2 ) ) ) How do I get associated tags along with the post. I know I am missing something, but unable to figure out. Any help would be highly appreciated.

    Read the article

  • CakePHP hasOne ineffeciency?

    - by Andre
    I was looking at examples on the CakePHP website, in particular hasOne used in linking models. http://book.cakephp.org/view/78/Associations-Linking-Models-Together My question is this, is CakePHP using two queries to build the array structure of data returned in a model that uses hasOne linkage? Taken from CakePHP: //Sample results from a $this-User-find() call. Array ( [User] => Array ( [id] => 121 [name] => Gwoo the Kungwoo [created] => 2007-05-01 10:31:01 ) [Profile] => Array ( [id] => 12 [user_id] => 121 [skill] => Baking Cakes [created] => 2007-05-01 10:31:01 ) ) Hope this all makes sense.

    Read the article

  • How to map it? HasOne x References

    - by Felipe
    Hi everyones, I need to make a mapping One by One, and I have some doubts. I have this classes: public class DocumentType { public virtual int Id { get; set; } /* othes properties for documenttype */ public virtual DocumentConfiguration Configuration { get; set; } public DocumentType () { } } public class DocumentConfiguration { public virtual int Id { get; set; } /* some other properties for configuration */ public virtual DocumentType Type { get; set; } public DocumentConfiguration () { } } A DocumentType object has only one DocumentConfiguration, but it is not a inherits, it's only one by one and unique, to separate properties. How should be my mappings in this case ? Should I use References or HasOne ? Someone could give an example ? When I load a DocumentType object I'd like to auto load the property Configuration (in documentType). Thanks a lot guys! Cheers

    Read the article

  • User HasOne ActiveToken, HasMany Tokens, how to setup in Rails?

    - by viatropos
    I have two simple models: class User < ActiveRecord::Base has_many :tokens # has_one doesn't work, because Token already stores # foreign id to user... # has_one :active_token, :class_name => "Token" # belongs_to doesn't work because Token belongs to # User already, and they both can't belong to each other # belongs_to :active_token, :class_name => "Token" end class Token < ActiveRecord::Base belongs_to :user end I want to say "User has_one :active_token, :class_name => 'Token'", but I can't because Token already belongs_to User. What I did instead was just manually add similar functionality to the user like so: class User < ActiveRecord::Base has_many :tokens attr_accessor :active_token after_create :save_active_token before_destroy :destroy_active_token # it belongs_to, but you can't have both belongs_to each other... def active_token return nil unless self.active_token_id @active_token ||= Token.find(self.active_token_id) end def active_token=(value) self.active_token_id = value.id @active_token = value end def save_active_token self.active_token.user = self self.active_token.save end def destroy_active_token self.active_token.destroy if self.active_token end end Is there a better way?

    Read the article

  • Doctrine: Unknown table alias. Is this DQL correct?

    - by ropstah
    I'm trying to execute a query but I get an error: Unknown table alias The tables are setup as follows: Template_Spot hasOne Template Template hasMany Template_Spot Template hasMany Location Location hasOne Template I'm trying to execute the following DQL: $locationid = 1; $spots = Doctrine_Query::create() ->select('cts.*, ct.*, uc.*') ->from('Template_Spot cts') ->innerJoin('Template ct') ->innerJoin('Location uc') ->where('uc.locationid = ?', $locationid)->execute(); Does anyone spot a problem?

    Read the article

  • PHP Doctrine: generation problem?

    - by ropstah
    I'm generating models from my Mysql db. It generates a foreign key collection properly, but not the other way around... Is this supposed to be 'by-design', or am i doing something wrong? pseudo code alert User: UserId pk LocationId fk //User location Location LocationId pk UserId fk //Location owner Generated code: class User() { hasMany('Location') //for locations owned by the user //BUT NOT THIS ONE: //hasOne('Location_1') //for current location of user } class Location() { hasMany('User') //for users which are on that location //AND NOT THIS ONE //hasOne('User_1') //for location owner }

    Read the article

  • Method for defining simultaneous has-many and has-one associations between two models in CakePHP?

    - by Hobonium
    One thing with which I have long had problems, within the CakePHP framework, is defining simultaneous hasOne and hasMany relationships between two models. For example: BlogEntry hasMany Comment BlogEntry hasOne MostRecentComment (where MostRecentComment is the Comment with the most recent created field) Defining these relationships in the BlogEntry model properties is problematic. CakePHP's ORM implements a has-one relationship as an INNER JOIN, so as soon as there is more than one Comment, BlogEntry::find('all') calls return multiple results per BlogEntry. I've worked around these situations in the past in a few ways: Using a model callback (or, sometimes, even in the controller or view!), I've simulated a MostRecentComment with: $this->data['MostRecentComment'] = $this->data['Comment'][0]; This gets ugly fast if, say, I need to order the Comments any way other than by Comment.created. It also doesn't Cake's in-built pagination features to sort by MostRecentComment fields (e.g. sort BlogEntry results reverse-chronologically by MostRecentComment.created. Maintaining an additional foreign key, BlogEntry.most_recent_comment_id. This is annoying to maintain, and breaks Cake's ORM: the implication is BlogEntry belongsTo MostRecentComment. It works, but just looks...wrong. These solutions left much to be desired, so I sat down with this problem the other day, and worked on a better solution. I've posted my eventual solution below, but I'd be thrilled (and maybe just a little mortified) to discover there is some mind-blowingly simple solution that has escaped me this whole time. Or any other solution that meets my criteria: it must be able to sort by MostRecentComment fields at the Model::find level (ie. not just a massage of the results); it shouldn't require additional fields in the comments or blog_entries tables; it should respect the 'spirit' of the CakePHP ORM. (I'm also not sure the title of this question is as concise/informative as it could be.)

    Read the article

  • Do ORMs normally allow circular relations? If so, how would they handle it?

    - by SeanJA
    I was hacking around trying to make a basic orm that has support for the one => one and one => many relationships. I think I succeeded somewhat, but I am curious about how to handle circular relationships. Say you had something like this: user::hasOne('car'); car::hasMany('wheels'); car::property('type'); wheel::hasOne('car'); You could then do this (theoretically): $u = new user(); echo $u->car->wheels[0]->car->wheels[1]->car->wheels[2]->car->wheels[3]->type; #=> "monster truck" Now, I am not sure why you would want to do this. It seems like it wastes a whole pile of memory and time just to get to something that could have been done in a much shorter way. In my small ORM, I now have 4 copies of the wheel class, and 4 copies of the car class in memory, which causes a problem if I update one of them and save it back to the database, the rest get out of date, and could overwrite the changes that were already made. How do other ORMs handle circular references? Do they even allow it? Do they go back up the tree and create a pointer to one of the parents? DO they let the coder shoot themselves in the foot if they are silly enough to go around in circles?

    Read the article

  • One-to-one Mapping issue with NHibernate/Fluent: Foreign Key not updateing

    - by Trevor
    Summary: Parent and Child class. One to one relationship between the Parent and Child. Parent has a FK property which references the primary key of the Child. Code as follows: public class NHTestParent { public virtual Guid NHTestParentId { get; set; } public virtual Guid ChildId { get { return ChildRef.NHTestChildId; } set { } } public virtual string ParentName { get; set; } protected NHTestChild _childRef; public virtual NHTestChild ChildRef { get { if (_childRef == null) _childRef = new NHTestChild(); return _childRef; } set { _childRef = value; } } } public class NHTestChild { public virtual Guid NHTestChildId { get; set; } public virtual string ChildName { get; set; } } With the following Fluent mappings: Parent Mapping Id(x => x.NHTestParentId); Map(x => x.ParentName); Map(x => x.ChildId); References(x => x.ChildRef, "ChildId").Cascade.All(); Child Mapping: Id(x => x.NHTestChildId); Map(x => x.ChildName); If I do something like (pseudo code) ... HTestParent parent = new NHTestParent(); parent.ParentName = "Parent 1"; parent.ChildRef.ChildName = "Child 1"; nhibernateSession.SaveOrUpdate(aParent); Commit; ... I get an error: "Invalid index 3 for this SqlParameterCollection with Count=3" If I change the parent 'References' line as follows (i.e. provide the name of the child property I'm pointing at): References(x => x.ChildRef, "ChildId").PropertyRef("NHTestChildId").Cascade.All(); I get the error: "Unable to resolve property: NHTestChildId" So, I tried the 'HasOne()' reference setting, as follows: HasOne<NHTestChild>(x => x.ChildRef).ForeignKey("ChildId").Cascade.All().Fetch.Join(); This results in the save working, but the load fails to find the child. If I inspect the SQL Nhibernate produces I can see that NHibernate is assuming the Primary key of the parent is the link to the child (i.e. load join condition is "parent.NHTestParentId = child.NHTestChildId). The 'ForeignKey' specified appears to be ignored. I can set any value and no error occurs - the join just always fails and no child is returned. I've tried a number of slight variations on the above. It seems like it should be a simple thing to achieve. Any ideas?

    Read the article

  • Map One-To-One Relationship Doesn't Allow Inserting

    - by nfplee
    Hi, I'm trying to setup a one-to-one mapping from my Users to the UserDetails table. Say I have the following tables in my database: Users: - UserID (PK, Identity) - UserName - Password UsersDetails: - UserID (PK, FK) - FirstName - LastName I have created the following poco classes: public class User { public virtual int UserID { get; set; } public virtual string UserName { get; set; } public virtual string Password { get; set; } public virtual UserDetails Details { get; set; } } public class UserDetails { public virtual int UserID { get; set; } public virtual User User { get; set; } public virtual string FirstName { get; set; } public virtual string LastName { get; set; } public UserDetails() { } public UserDetails(User user) { User = user; } } Which are fluently mapped (please note the xml mapping is very similar and if all you know is the xml mapping then I would still appreciate you guidance): public class UserMap : ClassMap<User> { public UserMap() { Table("Users"); Id(x => x.UserID); Map(x => x.UserName); Map(x => x.Password); HasOne(x => x.Details) .Constrained() .Cascade.All(); } } public class UserDetailsMap : ClassMap<UserDetails> { public UserDetailsMap() { Table("UsersDetails"); Id(x => x.UserID) .GeneratedBy.Foreign("User"); HasOne(x => x.User) .Constrained(); Map(x => x.FirstName); Map(x => x.LastName); } } Everything displays correctly but if I say: var user = new User() { UserName = "Test", Password = "Test" }; user.Details = new UserDetails(user) { FirstName = "Test", LastName = "Test" }; session.Save(user); I get the error: "NHibernate.Id.IdentifierGenerationException: null id generated for: UserDetails." I'd really appreciate it if someone could show me what I've done wrong. Thanks

    Read the article

  • Fluent Nhibernate - Mapping child in parent when Child has reference to parent and not using a list

    - by Josh
    I have a child object in the database that looks like this: CREATE TABLE Child ( ChildId uniqueidentifier not null, ParentId uniqueidentifier not null ) An then I have a parent like so. CREATE TABLE Parent ( ParentId uniqueidentifier not null ) Now, the problem is that in my Parent class, I have public virtual Child Child { get; set; } I've tried references, hasone, referencesany and can't seem to get the mapping right. Anyone have any ideas? Thanks,

    Read the article

  • help with generating models from database for many to many in doctrine

    - by ajsie
    im using doctrine and i have set up some test tables to be generated into models: I want a many-to-many relationship models (3 tables converted into 3 models) (things are simplified to make the point clear) mysql tables: user: id INT // primary key name VARCHAR group: id INT // primary key name VARCHAR user_group: user_id INT // primary and foreign key to user.id group_id INT // primary and foreign key to group.id i thought that it would generate these models (from the documentation): // User.php class User extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('id'); $this->hasColumn('name); } public function setUp() { $this->hasMany('Group as Groups', array( 'refClass' => 'UserGroup', 'local' => 'user_id', 'foreign' => 'group_id' ) ); } } // Group.php class Group extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('id'); $this->hasColumn('name); } public function setUp() { $this->hasMany('User as Users', array( 'refClass' => 'UserGroup', 'local' => 'group_id', 'foreign' => 'user_id' ) ); } } // UserGroup.php class UserGroup extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('user_id') ); $this->hasColumn('group_id') ); } } but it generated this: // User.php abstract class BaseUser extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('id'); $this->hasColumn('name'); } public function setUp() { $this->hasMany('UserGroup', array( 'local' => 'id', 'foreign' => 'user_id')); } } // Group.php abstract class BaseGroup extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('id'); $this->hasColumn('name'); } public function setUp() { $this->hasMany('UserGroup', array( 'local' => 'id', 'foreign' => 'group_id')); } } // UserGroup.php abstract class BaseUserGroup extends Doctrine_Record { public function setTableDefinition() { $this->hasColumn('user_id'); $this->hasColumn('group_id'); } public function setUp() { $this->hasOne('User', array( 'local' => 'user_id', 'foreign' => 'id')); $this->hasOne('Group', array( 'local' => 'group_id', 'foreign' => 'id')); } } as you can see, there is no 'refClass' in the 'User' and 'Group' models pointing to the 'UserGroup'. the 'UserGroup' table in this case is just another table from Doctrine's perspective not a reference table. I've checked my table definitions in mysql. They are correct. user_group has 2 columns (primary keys and foreign keys), each one pointing to the primary key in either User or Group. But i want the standard many-to-many relationship models in Doctrine models. I'd appreciate some help. I have struggled to figure it out for a half day now. What is wrong? Thanks!

    Read the article

  • CakePHP: shortcomings with indirectly associated models

    - by Dan
    I'm having some issues with dealing with indirectly associated models in cakephp. My current model setup is as follows: Deliveries hasOne License License belongsTo Delivery License hasAndBelongsToMany Product (and vice-versa) License hasAndBelongsToMany ProductOption (and vice-versa) I'm trying to save information about ALL of these models inside ONE form. The shortcomings I'm running into are the following: The form helper only seems able to see the field type one level deep. saveAll() only seems able to save records one level deep (for multiple model forms). I'm searching everywhere for the solutions to these issues, but since I'm new to CakePHP, I'm not sure what the newest methods or "correct" methods are for dealing with these issues. Any advice is much appreciated. Thank you all! EDIT: I've posted code to my failed attempt here: http://bin.cakephp.org/saved/58501

    Read the article

  • Want to save data field from form into two columns of two models.

    - by vette982
    I have a Profile model with a hasOne relationship to a Detail model. I have a registration form that saves data into both model's tables, but I want the username field from the profile model to be copied over to the usernamefield in the details model so that each has the same username. function new_account() { if(!empty($this->data)) { $this->Profile->modified = date("Y-m-d H:i:s"); if($this->Profile->save($this->data)) { $this->data['Detail']['profile_id'] = $this->Profile->id; $this->data['Detail']['username'] = $this->Profile->username; $this->Profile->Detail->save($this->data); $this->Session->setFlash('Your registration was successful.'); $this->redirect(array('action'=>'index')); } } } This code in my Profile controller gives me the error: Undefined property: Profile::$username Any ideas?

    Read the article

  • Cakephp, i18n, SQL Error, Not unique table/alias

    - by ion
    I get the following SQL error: SQL Error: 1066: Not unique table/alias: 'I18n__name' when doing a simple find query. Any ideas on possible situations that may have caused this?? I'm using a bindModel method to retrieve the data is that related? This is my code: $this->Project->bindModel(array( 'hasOne' => array( 'ProjectsCategories', 'FilterCategory' => array( 'className' => 'Category', 'foreignKey' => false, 'conditions' => array('FilterCategory.id = ProjectsCategories.category_id') )))); $prlist = $this->Project->find('all', array( 'fields' => array('DISTINCT slug','name'), 'conditions' => array('FilterCategory.slug !='=>'uncategorised') ))

    Read the article

  • Fluent NHibernate auto mapping: map property from another table's column

    - by queen3
    I'm trying to use S#arp architecture... which includes Fluent NHibernate I'm newbie with (and with NHibernate too, frankly speaking). Auto mapping is used. So I have this: public class UserAction : Entity { public UserAction() { } [DomainSignature] [NotNull, NotEmpty] public virtual string Name { get; set; } [NotNull, NotEmpty] public virtual string TypeName { get; private set; } } public class UserActionMap : IAutoMappingOverride<UserAction> { public void Override(AutoMap<UserAction> mapping) { mapping.WithTable("ProgramComponents", m => m.Map(x => x.TypeName)); } } Now, table UserActions references table ProgramComponents (many to one) and I want property UserAction.TypeName to have value from db field ProgramComponents.TypeName. However, the above code fails with NHibernate.MappingException: Duplicate property mapping of TypeName found in OrderEntry3.Core.UserAction As far as I understand the problem is that TypeName is already auto-mapped... but I haven't found a way to remove the automatic mapping. Actually I think that my WithTable/Map mapping has to replace the automatic TypeName mapping, but seems like it does not. I also tried different mapping (names are different but that's all the same): mapping.WithTable("ProgramComponents", m => m.References<ProgramComponent>( x => x.Selector, "ProductSelectorID" ) and still get the same error. I can overcome this with mapping.HasOne<ProgramComponent>(x => x.Selector); but that's not what I exactly wants to do. And I still wonder why the first two methods do not work. I suspect this is because of WithTable.

    Read the article

  • Laravel 4 showing all field from one to one relationship in

    - by rivai04
    I'm trying to show all field of the chosen row from one to one relationship... Route Route::get('relasi-pasien', function() { $pasien = PasienIri::where('no_ipd', '=', '100')->first(); foreach($pasien->keadaanumum as $temp) { echo'<li> Name : '.$temp->name. 'Tekdar: '.$temp->tekdar. 'Nadi : '.$temp->nadi. '</li>'; } }); Relation at PasienIri's model public function keadaanumum() { return $this->hasOne('KeadaanUmum', 'no_ipd'); } Relation at KeadaanUmum's Model public function pasieniri() { return $this->belongsTo('PasienIri', 'no_ipd'); } When I used that way, it showed error: 'Trying to get property of non-object' But if I just trying to show only one of the field, it works, showing one field: Route::get('relasi-pasien', function() { $pasien = PasienIri::where('no_ipd', '=', '100')->first(); return $pasien->keadaanumum->name; }); anyone could help me to show all field with one to one relationship or I really have to change it to one to many relationship? cause if I change it to one to many relationship, it works

    Read the article

  • NHibernate One to One Foreign Key ON DELETE CASCADE

    - by xll
    I need to implement One-to-one association between Project and ProjecSettings using fluent NHibernate: public class ProjectMap : ClassMap<Project> { public ProjectMap() { Id(x => x.Id) .UniqueKey(MapUtils.Col<Project>(x => x.Id)) .GeneratedBy.HiLo("NHHiLoIdentity", "NextHiValue", "1000", string.Format("[EntityName] = '[{0}]'", MapUtils.Table<Project>())) .Not.Nullable(); HasOne(x => x.ProjectSettings) .PropertyRef(x => x.Project); } } public class ProjectSettingsMap : ClassMap<ProjectSettings> { public ProjectSettingsMap() { Id(x => x.Id) .UniqueKey(MapUtils.Col<ProjectSettings>(x => x.Id)) .GeneratedBy.HiLo("NHHiLoIdentity", "NextHiValue", "1000", string.Format("[EntityName] = '[{0}]'", MapUtils.Table<ProjectSettings>())); References(x => x.Project) .Column(MapUtils.Ref<ProjectSettings, Project>(p => p.Project, p => p.Id)) .Unique() .Not.Nullable(); } } This results in the following sql for Project Settings: CREATE TABLE ProjectSettings ( Id bigint PRIMARY KEY NOT NULL, Project_Project_Id bigint NOT NULL UNIQUE, /* Foreign keys */ FOREIGN KEY (Project_Project_Id) REFERENCES Project() ON DELETE NO ACTION ON UPDATE NO ACTION ); What I am trying to achieve is to have ON DELETE CASCADE for the FOREIGN KEY (Project_Project_Id), so that when the project is deleted through sql query, it's settings are deleted too. How can I achieve this ? EDIT: I know about Cascade.Delete() option, but it's not what I need. Is there any way to intercept the FK statement generation?

    Read the article

  • CakePHP: Need help using saveField to update a fields in a belongsTo model

    - by afrisch
    I am trying to update a password into two different models/tables in CakePHP. I can update it fine in the parent model, but not the second model. Models: Users (hasOne GameProfile) PK=id Gameprofiles (belongsTo User) FK=user_id Here is a stripped down version of my function in the Users_controller.php: function updatepass() { if (!empty($this->data)) { $this->User->id = $this->Auth->user('id'); $this->User->saveField('sha1password', $this->Auth->password($this->data['User']['newpass'])); $this->User->Gameprofile->saveField('plainpassword', $this->data['User']['newpass']); } } When I execute the function, the users table is updated fine. But the gameprofile table is not updated, rather Cake does an insert. SQL Query Log: 1195 Query UPDATE `users` SET `sha1password` = 'e9443e9f5e1a07832aad1b2f84de1a666daf89b5' WHERE `users`.`id` = 30 1195 Query INSERT INTO `gameprofiles` (`plainpassword`) VALUES ('abc') Is there a way to get CakePHP to do an update using saveField on a model with a belongsTo attribute? I've tried various ways to refer to user_id before executing the second saveField, but just can't seem to find the winning combination. Any help is greatly appreciated!

    Read the article

  • Grails one-to-many mapping with joinTable

    - by intargc
    I have two domain-classes. One is a "Partner" the other is a "Customer". A customer can be a part of a Partner and a Partner can have 1 or more Customers: class Customer { Integer id String name static hasOne = [partner:Partner] static mapping = { partner joinTable:[name:'PartnerMap',column:'partner_id',key:'customer_id'] } } class Partner { Integer id static hasMany = [customers:Customer] static mapping = { customers joinTable:[name:'PartnerMap',column:'customer_id',key:'partner_id'] } } However, whenever I try to see if a customer is a part of a partner, like this: def customers = Customer.list() customers.each { if (it.partner) { println "Partner!" } } I get the following error: org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute query; SQL [select this_.customer_id as customer1_162_0_, this_.company as company162_0_, this_.display_name as display3_162_0_, this_.parent_customer_id as parent4_162_0_, this_.partner_id as partner5_162_0_, this_.server_id as server6_162_0_, this_.status as status162_0_, this_.vertical_market as vertical8_162_0_ from Customer this_]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query It looks as if Grails is thinking partner_id is a part of the Customer query, and it's not... It is in the PartnerMap table, which is supposed to find the customer_id, then get the Partner from the corresponding partner_id. Anyone have any clue what I'm doing wrong? Edit: I forgot to mention I'm doing this with legacy database tables. So I have a Partner, Customer and PartnerMap table. PartnerMap has simply a customer_id and partner_id field.

    Read the article

  • Nhibernate: One-To-Many mapping problem - Cannot cascade delete without inverse. Set NULL error

    - by KnaveT
    Hi, I have the current scenario whereby an Article has only 1 Outcome each. Each Article may or may not have an Outcome. In theory, this is a one-to-one mapping, but since NHibernate does not really support one-to-one, I used a One-To-Many to substitute. My Primary Key on the child table is actually the ArticleID (FK). So I have the following setup: Classes public class Article { public virtual Int32 ID { get;set;} private ICollection<ArticleOutcome> _Outcomes {get;set;} public virtual ArticleOutcome Outcome { get { if( this._Outcomes !=null && this._Outcomes.Count > 0 ) return this._Outcomes.First(); return null; } set { if( value == null ) { if( this._Outcomes !=null && this._Outcomes.Count > 0 ) this._Outcomes.Clear(); } else { if( this._Outcomes == null ) this._Outcomes = new HashSet<ArticleOutcome>(); else if ( this._Outcomes.Count >= 1 ) this._Outcomes.Clear(); this._Outcomes.Add( value ); } } } } public class ArticleOutcome { public virtual Int32 ID { get;set; } public virtual Article ParentArticle { get;set;} } Mappings public class ArticleMap : ClassMap<Article> { public ArticleMap() { this.Id( x=> x.ID ).GeneratedBy.Identity(); this.HasMany<ArticleOutcome>( Reveal.Property<Article>("_Outcomes") ) .AsSet().KeyColumn("ArticleID") .Cascade.AllDeleteOrphan() //Cascade.All() doesn't work too. .LazyLoad() .Fetch.Select(); } } public class ArticleOutcomeMap : ClassMap<ArticleOutcome> { public ArticleOutcomeMap(){ this.Id( x=> x.ID, "ArticleID").GeneratedBy.Foreign("ParentArticle"); this.HasOne( x=> x.ParentArticle ).Constrained (); //This do not work also. //this.References( x=> x.ParentArticle, "ArticleID" ).Not.Nullable(); } } Now my problem is this: It works when I do an insert/update of the Outcome. e.g. var article = new Article(); article.Outcome = new ArticleOutcome { xxx = "something" }; session.Save( article ); However, I encounter SQL errors when attempting to delete via the Article itself. var article = session.Get( 123 ); session.Delete( article ); //throws SQL error. The error is something to the like of Cannot insert NULL into ArticleID in ArticleOutcome table. The deletion works if I place Inverse() to the Article's HasMany() mapping, but insertion will fail. Does anyone have a solution for this? Or do I really have to add a surrogate key to the ArticleOutcome table?

    Read the article

  • Does CakePHP treat all INT fields as ID's for join tables?

    - by Jonnie
    I am trying to save a User, their Profile, and some tags and my join table that links the profile and the tags keeps getting messed up. The profile model is called Instructor, the tag model is called Subject. The Instructor has a phone number and a zip code and for some reason CakePHP thinks these are the fields it should use when creating entries in my join table. My Join table always comes out as: id | instructor_id | subject_id | 1 | 90210 | 1 | // thinks that the zip code is an instructor_id 2 | 1112223333 | 1 | // thinks that the phone number is an instructor_id 3 | 1 | 1 | // thinks that user_id is an instructor_id 4 | 1 | 1 | // the actual instructor_id, this one's correct 5 | 90210 | 2 | 6 | 1112223333 | 2 | 3 | 1 | 2 | 4 | 1 | 2 | My Models: class Instructor extends AppModel { var $name = 'Instructor'; var $belongsTo = array('User', 'State'); var $hasAndBelongsToMany = array( 'Subject' = array( 'className' = 'Subject', 'joinTable' = 'instructors_subjects', 'foreignKey' = 'instructor_id', 'associationForeignKey' = 'subject_id', 'unique' = true, 'conditions' = '', 'fields' = '', 'order' = '', 'limit' = '', 'offset' = '', 'finderQuery' = '', 'deleteQuery' = '', 'insertQuery' = '' ) ); } class Subject extends AppModel { var $name = 'Subject'; var $hasAndBelongsToMany = array( 'Instructor' = array( 'className' = 'Instructor', 'joinTable' = 'instructors_subjects', 'foreignKey' = 'subject_id', 'associationForeignKey' = 'instructor_id', 'unique' = true, 'conditions' = '', 'fields' = '', 'order' = '', 'limit' = '', 'offset' = '', 'finderQuery' = '', 'deleteQuery' = '', 'insertQuery' = '' ) ); } My Model Associations: User hasOne Instructor Instructor belongsTo User Instructor hasAndBelongsToMany Subject Subject hasAndBelongsToMany Instructor My form data looks like: Array ( [User] = Array ( [username] = MrInstructor [password] = cddb06c93c72f34eb9408610529a34645c29c55d [group_id] = 2 ) [Instructor] = Array ( [name] = Jimmy Bob [email] = [email protected] [phone] = 1112223333 [city] = Beverly Hills [zip_code] = 90210 [states] = 5 [website] = www.jimmybobbaseballschool.com [description] = Jimmy Bob is an instructor. [user_id] = 1 [id] = 1 ) [Subject] = Array ( [name] = hitting, pitching ) ) My function for processing the form looks like: function instructor_register() { $this-set('groups', $this-User-Group-find('list')); $this-set('states', $this-User-Instructor-State-find('list')); if (!empty($this-data)) { // Set the group to Instructor $this-data['User']['group_id'] = 2; // Save the user data $user = $this-User-save($this-data, true, array( 'username', 'password', 'group_id' )); // If the user was saved, save the instructor's info if (!empty($user)) { $this-data['Instructor']['user_id'] = $this-User-id; $instructor = $this-User-Instructor-save($this-data, true, array( 'user_id', 'name', 'email', 'phone', 'city', 'zip_code', 'state_id', 'website', 'description' )); // If the instructor was saved, save the rest if(!empty($instructor)) { $instructorId = $this-User-Instructor-id; $this-data['Instructor']['id'] = $instructorId; // Save each subject seperately $subjects = explode(",", $this-data['Subject']['name']); foreach ($subjects as $_subject) { // Get the correct subject format $_subject = strtolower(trim($_subject)); $this-User-Instructor-Subject-create($this-data); $this-User-Instructor-Subject-set(array( 'name' = $_subject )); $this-User-Instructor-Subject-save(); echo ''; print_r($this-data); echo ''; } } } } }

    Read the article

1