envms / fluentpdo

A PHP SQL query builder using PDO
http://envms.github.io/fluentpdo/
926 stars 189 forks source link

Can i change primaryKey per query? #301

Open liorphp opened 5 years ago

liorphp commented 5 years ago

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.

cbornhoft commented 5 years ago

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.

liorphp commented 5 years ago

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.

cbornhoft commented 5 years ago

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.