Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Primary Key on Model Cannot be Changed (Model with Complex PK)
  • First off, thanks for Fuel.  It's a great framework!  

    I've been banging my head with this ORM error:
    Fuel\Core\FuelException [ Error ]: Primary key on model Model_CustomValue cannot be changed.

    Here are relevant info from my models I'm having issues with:

         <?php
        use Orm\Model;
        
        class Model_Purchase extends Model
        {
            protected static $_has_many = array(
                'customvalues' => array(
                    'model_to' => 'Model_CustomValue',
                    'key_to' => 'purchase_id',
                    'cascade_delete' => true,
                )
            );
        
            protected static $_properties = array(
                'id',
                'customer_id',
                'payment_id',
                'audit_id',
                'created_at',
                'updated_at',
            );
        
        
        <?php
        use Orm\Model;
        
        class Model_CustomValue extends Model
        {
            protected static $_table_name = 'customvalues';
            protected static $_primary_key = array('purchase_id', 'customfield_id');
        
            protected static $_belongs_to = array(
                'purchase' => array(
                    'key_from' => 'purchase_id',
                    'model_to' => 'Model_Purchase',
                    'key_to' => 'id',
                ),
            );
        

    When trying to save the Model_Purchase with an array of Model_CustomValue objects as a property named 'customvalues' on the $purchase object, I get the "Primary key on model Model_CustomValue cannot be changed."

    I've tried putting swapping the key_from/to in the "belongs_to" on the Model_CustomValue, but to no avail.

    I'm using Fuel 1.6 (hash: 6e6d764)

    Any tips you can provide would be greatly appreciated -- donate to hosting costs, or whatever.
  • HarroHarro
    Accepted Answer
    You can not have a column which is at the same time FK and PK. Which you have on your Model_CustomValue.

    The reason for that is that when you disconnect a relation, the FK will be set to NULL, which should not happen with a PK.
  • I've added this issue to the todo list of the v2 ORM.
  • Thanks for the quick response Harro!

    So just re-stating why that's not allowed:
    Model_CustomValue uses the "purchase_id" as part of its PK as well as the FK to Model_Purchase.  And if the two Models were to be unlinked, that would lead to a null portion of the PK for Model_CustomValue -- which obviously isn't allowed.

    Can you confirm my understanding there?

    Thanks!
  • Correct.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion