Skip to content

Commit ea0e717

Browse files
committed
fix for table prefix being supplied.
1 parent 94fd5cd commit ea0e717

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

src/ActiveRecord.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -716,8 +716,11 @@ public function addCondition(string $field, string $operator, $value, string $de
716716
$value = $this->filterParam($value);
717717
}
718718
$name = strtolower($name);
719+
720+
// skip adding the `table.` prefix if it's already there or a function is being supplied.
721+
$skip_table_prefix = (strpos($field, '.') !== false || strpos($field, '(') !== false);
719722
$expressions = new Expressions([
720-
'source' => ('where' === $name ? $this->table . '.' : '') . $field,
723+
'source' => ('where' === $name && $skip_table_prefix === false ? $this->table . '.' : '') . $field,
721724
'operator' => $operator,
722725
'target' => (
723726
is_array($value)

tests/ActiveRecordPdoIntegrationTest.php

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -624,4 +624,53 @@ public function testTextBasedPrimaryKeyDuplicateKey() {
624624
$this->expectExceptionMessage('UNIQUE constraint failed: my_text_table.my_pk');
625625
$myTextTable2->save();
626626
}
627+
628+
public function testWhereConditionWithSuppliedTableName() {
629+
$user = new User(new PDO('sqlite:test.db'));
630+
$user->name = 'demo';
631+
$user->password = md5('demo');
632+
$user->insert();
633+
634+
$contact = new Contact(new PDO('sqlite:test.db'));
635+
$contact->user_id = $user->id;
636+
$contact->email = '[email protected]';
637+
$contact->address = 'test address';
638+
$contact->insert();
639+
640+
$user
641+
->select('user.*, contact.email')
642+
->join('contact', 'contact.user_id = user.id')
643+
->eq('user.name', 'demo')
644+
->find();
645+
646+
$this->assertEquals('demo', $user->name);
647+
$this->assertEquals('[email protected]', $user->email);
648+
}
649+
650+
public function testWhereConditionWithFunctionName() {
651+
652+
$this->ActiveRecord->execute("CREATE TABLE IF NOT EXISTS json_test (
653+
id INTEGER PRIMARY KEY,
654+
data TEXT,
655+
created_dt TEXT
656+
);");
657+
658+
$json = new class(new PDO('sqlite:test.db')) extends ActiveRecord {
659+
public function __construct($pdo) {
660+
parent::__construct($pdo);
661+
$this->table = 'json_test';
662+
$this->primaryKey = 'id';
663+
}
664+
};
665+
$json->data = '{"name": "demo", "email": "[email protected]"}';
666+
$json->created_dt = gmdate('Y-m-d H:i:s');
667+
$json->insert();
668+
$json
669+
->select('json_test.*, json_extract(data, "$.email") as email')
670+
->eq('json_extract(data, "$.name")', 'demo')
671+
->find();
672+
673+
$this->assertEquals('demo', json_decode($json->data)->name);
674+
$this->assertEquals('[email protected]', $json->email);
675+
}
627676
}

0 commit comments

Comments
 (0)