ColBatGuano's avatar

Get primary key field name?

Is there any way to get the primary key field name of a class from outside the class? Or in a static context?

0 likes
4 replies
GeordieJackson's avatar
Level 18

You can add a static method to the model and return the primary key:

public static function primaryKey()
{
    return (new static())->getPrimaryKey();
}

and fetch it with: $primaryKey = ModelName::primaryKey();

GeordieJackson's avatar

Or...

You could hard code the key name into a constant, use that to set the field in the class, and then you'd be able to access the key without having to instantiate the class. e.g.

    class Test extends Model
    {
        const PRIMARYKEY = 'id';

        protected $primaryKey = self::PRIMARYKEY;
    }

It can be accessed with: $key = Test::PRIMARYKEY

You would have to change the const value if you ever changed the key but that's straightforward and unlikely to be required anyway once the key has been chosen.

Snapey's avatar

just call the model's getKeyName() function

or (new Model)->getKeyName()

3 likes
ColBatGuano's avatar

Thanks for the answers.

Makes me wonder why it isn't a static attribute. Why should there be an instance of the $primaryKey for -every- object created when it should just be the one value for the class.

E.g.

protected static $primaryKey = "...";

Please or to participate in this conversation.