We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 11793
    • 49 Posts
    Just a quick question to Jason:

    Lets say we have one table set up as an xPDOSimpleObject:

    <object class="CoCarts" table="co_carts" extends="xPDOSimpleObject">
    		... lots of fields here...
    <composite alias="Products" class="CoCartProducts" local="id" foreign="cart_id" cardinality="many" owner="local" />
    	</object>


    And one table set up with no Primary Key - an xPDOObject:
    <object class="CoCartProducts" table="co_cart_products" extends="xPDOObject">
    		... lots of fields here...
    		<aggregate alias="Cart" class="CoCarts" local="cart_id" foreign="id" cardinality="one" owner="foreign" />
    	</object>

    And then we try and do this:
    $Cart= $xpdo->getObject('CoCarts',$validId);
    $Cart->getMany('Products');
    echo count($Cart->Products);
    

    And the result is zero, when the database says that there is one record in there with a matching FK of ’cart_id’. And yes, hydration is turned on.

    The question is: Is this problem caused by the absence of a Primary Key field? huh

    I ask this because the above code was working fine (as you imagine) when the table CoCartProducts had a primary key. I deleted the primary key since it served no purpose other than to threaten to hit the maximum integer limit rather quickly.
    • The answer is simply, you have to have a primary key field (or fields). A table without a primary key defined is, well, worthless.
        • 28215
        • 4,149 Posts
        hardboiled,

        In your specific circumstance, you could make CoCartProducts have a PK of a unique identifier - such as the SKU, or ID in your inventory. Then in your CoCartProduct creation scripts, you could make sure to validate that items dont get created with the same SKU/ID.
          shaun mccormick | bigcommerce mgr of software engineering, former modx co-architect | github | splittingred.com
          • 11793
          • 49 Posts
          Yeah, I ended up switching back to having a PK. The only reason I took it off is because it served no function - two columns together served as a combination primary key. Maybe there is a way to set that up in MySQL, but I just don’t know it.

          Also, the table was looking to have high record turnover - lots of deletes and inserts. I changed the logic so that there are no deletes and a sane amount of inserts, so no threat of running out of PK IDs.
          • In xPDO just define two columns as the PK in your schema and regenerate the maps. In MySQL you can add a PK on multiple columns easily by running ALTER TABLE `tablename` ADD PRIMARY KEY (`col1`,`col2`). Just make sure you drop any existing PRIMARY KEY definition first. Also, make sure you define the compound primary key in the order the columns exist in the table.