fluentpdo icon indicating copy to clipboard operation
fluentpdo copied to clipboard

Can i change primaryKey per query?

Open liorphp opened this issue 5 years ago • 3 comments

When i use this line: $this->_db->from($this->getTable(), $id)->fetch()

$id is the value of "primaryKey" column, the default is 'id', by: lichtner\fluentpdo\src\Structure.php line 22 (Structure constructor).

This constructor activate when i set the fluentpdo object. Can i set diffrent primaryKey OR Structure object per query?

I see the method getStructure on Query.php I search something like setStructure method.

Thanks.

liorphp avatar Oct 16 '19 19:10 liorphp

Yes, you can supply your own structure and pass it to the constructor of Query!

use Envms\FluentPDO\{Query, Structure};

$myStructure = new Structure('customId', 'foreignId');
$fluent = new Query($pdo, $myStructure);

It also supports custom callables if you want to get a little more complex:

$callable = 
    function($prefix)
    {
        $len = strlen($prefix);
        return "{$prefix}_{$len}";
    };

$myStructure = new Structure($callable, 'foreignId');

In the example above, if your main table name was archive, your primary key would be returned as archive_7.

cbornhoft avatar Oct 17 '19 01:10 cbornhoft

I know that, but it's global solution. I have difference primaryKey each table.

I dont do it on new Query(), i want to do it on any query.

liorphp avatar Oct 17 '19 11:10 liorphp

Can you provide an example of these different primary keys? With callbacks available, essentially any naming you have can be created dynamically, regardless if the structure is only provided once.

cbornhoft avatar Oct 19 '19 01:10 cbornhoft