Question

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 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)

Please let me know if more information would be helpful, and I'll provide.

Was it helpful?

Solution

From the FuelPHP forum thread, Harro answered:

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 then clarified, for those of us who may need specific examples from the original example, I confirmed the following:

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top