Skip to content

Commit 0ef34f7

Browse files
committed
fix: _query 支持子查询操作
1 parent 548e80e commit 0ef34f7

File tree

1 file changed

+22
-5
lines changed

1 file changed

+22
-5
lines changed

src/Helper.php

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -90,15 +90,22 @@ public static function instance(...$args): Helper
9090
public static function buildQuery($query)
9191
{
9292
if (is_string($query)) {
93-
return static::buildModel($query)->db();
93+
if (self::isSubquery($query)) {
94+
$query = Library::$sapp->db->table($query);
95+
} else {
96+
return static::buildModel($query)->db();
97+
}
9498
}
9599
if ($query instanceof Model) return $query->db();
96100
if ($query instanceof BaseQuery && !$query->getModel()) {
97-
$name = $query->getConfig('name') ?: '';
98-
if (is_string($name) && strlen($name) > 0) {
99-
$name = config("database.connections.{$name}") ? $name : '';
101+
// 如果是子查询,不需要挂载模型对象
102+
if (!self::isSubquery($query->getTable())) {
103+
$name = $query->getConfig('name') ?: '';
104+
if (is_string($name) && strlen($name) > 0) {
105+
$name = config("database.connections.{$name}") ? $name : '';
106+
}
107+
$query->model(static::buildModel($query->getName(), [], $name));
100108
}
101-
$query->model(static::buildModel($query->getName(), [], $name));
102109
}
103110
return $query;
104111
}
@@ -121,4 +128,14 @@ public static function buildModel(string $name, array $data = [], string $conn =
121128
}
122129
return VirtualModel::mk($name, $data, $conn);
123130
}
131+
132+
/**
133+
* 判断是否为子查询
134+
* @param string $sql
135+
* @return bool
136+
*/
137+
private static function isSubquery(string $sql): bool
138+
{
139+
return preg_match('/^\(?\s*select\s+/i', $sql) > 0;
140+
}
124141
}

0 commit comments

Comments
 (0)