Skip to content

Commit b86f0bf

Browse files
committed
改进复合主键查询
1 parent 557101b commit b86f0bf

File tree

3 files changed

+31
-8
lines changed

3 files changed

+31
-8
lines changed

src/Entity.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1055,7 +1055,14 @@ public function setKey($value)
10551055
public function getKey()
10561056
{
10571057
$pk = $this->getPk();
1058-
return is_string($pk) ? $this->get($pk) : null;
1058+
if (is_string($pk)) {
1059+
return $this->get($pk);
1060+
}
1061+
1062+
foreach ($pk as $name) {
1063+
$data[$name] = $this->get($name);
1064+
}
1065+
return $data;
10591066
}
10601067

10611068
/**

src/db/BaseQuery.php

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1400,7 +1400,11 @@ public function delete($data = null): int
14001400
if ($this->model && $this->model instanceof Model) {
14011401
$this->where($this->model->getWhere());
14021402
} elseif (!empty($this->options['key'])) {
1403-
$this->where($this->pk, '=', $this->options['key']);
1403+
if (is_array($this->pk)) {
1404+
$this->where($this->options['key']);
1405+
} else {
1406+
$this->where($this->pk, '=', $this->options['key']);
1407+
}
14041408
}
14051409
}
14061410

@@ -1580,7 +1584,11 @@ public function parseUpdateData(array &$data): bool
15801584
$isUpdate = false;
15811585
// 如果存在主键数据 则自动作为更新条件
15821586
if (!empty($this->options['key'])) {
1583-
$this->where($pk, '=', $this->options['key']);
1587+
if (is_array($pk)) {
1588+
$this->where($this->options['key']);
1589+
} else {
1590+
$this->where($pk, '=', $this->options['key']);
1591+
}
15841592
$isUpdate = true;
15851593
} elseif (is_string($pk) && isset($data[$pk])) {
15861594
$this->where($pk, '=', $data[$pk]);

src/model/concern/Attribute.php

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -217,10 +217,10 @@ protected function isPk(string $key): bool
217217
public function setKey($value)
218218
{
219219
$pk = $this->getPk();
220-
if (is_string($pk)) {
221-
$this->key = $value;
222-
$this->exists = true;
223-
}
220+
221+
$this->key = $value;
222+
$this->exists = true;
223+
224224
return $this;
225225
}
226226

@@ -239,8 +239,16 @@ public function getKey()
239239

240240
if (is_string($pk) && array_key_exists($pk, $this->data)) {
241241
$this->key = $this->data[$pk];
242-
return $this->data[$pk];
242+
} elseif (is_array($pk)) {
243+
$data = [];
244+
foreach ($pk as $name) {
245+
if (array_key_exists($name, $this->data)) {
246+
$data[$name] = $this->data[$name];
247+
}
248+
}
249+
$this->key = $data;
243250
}
251+
return $this->key ?? null;
244252
}
245253

246254
/**

0 commit comments

Comments
 (0)