Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

doctrine relation on integer field returns string

My schema.yml

Organisation:
  columns:
    id: { type: integer(4), notnull: true, unique: true, primary: true, autoincrement: true }
    name: { type: string(100), notnull: true, unique: true }
    parent_organisation_id: { type: integer(4), notnull: false }

  relations:
    ParentOrganisation: { class: Organisation, local: parent_organisation_id, foreignAlias: ChildOrganisations }

Some organisations have the integer value 0 stored and there is no such organisation_id. To my surprise when I run this code

class organisationActions extends autoOrganisationActions{

    public function executeEdit(sfWebRequest $request){

        $this->organisation = $this->getRoute()->getObject();
        $p = $this->organisation->getParentOrganisationId();
        var_dump($p);

The result is string(1) "0"

Why does this not return an integer, so I can compare === 0

like image 869
jdog Avatar asked Oct 21 '22 10:10

jdog


1 Answers

I do some test and I see that every value of an entity are returned via magic call that the parent class of every Entity model sfDoctrineRecord do in the _call method. So the return type of the call_user_func_array seem don't distinct against string or int etc. The same behaviour we have on every field of every entity so implemented, the id field also.

So, as workaround, you can implement your custom getter for check if the records is null or is the first (id=0) for compare operation as follow:

class Organisation extends BaseOrganisation
{

        public function getParentIdAsIntegerOrNullOtherwise()
        {
            $an_id = $this->getParentOrganisationId();

            if (! is_null($an_id))
            {
                return intval($an_id);
            }

            return NULL;
        }
    }

In the controller:

    $p = $this->organisation->getParentIdAsIntegerOrNullOtherwise();

    var_dump($p);

It will dump

NULL

if is not linked to any parent node

and will dump

int(0)

if this is linked to the element with id = 0

Hope this help

Let me know what you think about it

like image 133
Matteo Avatar answered Oct 24 '22 04:10

Matteo