改进模型类对主键的自动读取

This commit is contained in:
thinkphp
2016-04-27 12:42:57 +08:00
parent 8cb52f60dd
commit 6915f0249e
2 changed files with 9 additions and 8 deletions

View File

@@ -30,7 +30,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
protected static $event = [];
// 数据表主键 复合主键使用数组定义
protected $pk = 'id';
protected $pk;
// 错误信息
protected $error;
// 当前模型名称
@@ -177,7 +177,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
*/
public function getPk($table = '')
{
if (!$this->pk) {
if (empty($this->pk)) {
$this->pk = self::db()->getTableInfo($table, 'pk');
}
return $this->pk;
@@ -272,8 +272,9 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
// 获取自动增长主键
if ($result && $getInsertId) {
$insertId = self::db()->getLastInsID();
if (is_string($this->pk) && $insertId) {
$this->data[$this->pk] = $insertId;
$pk = $this->getPk();
if (is_string($pk) && $insertId) {
$this->data[$pk] = $insertId;
}
}
// 新增回调
@@ -731,7 +732,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
{
// 记录当前关联信息
$model = $this->parseModel($model);
$localKey = $localKey ?: $this->pk;
$localKey = $localKey ?: $this->getPk();
$foreignKey = $foreignKey ?: Loader::parseName($this->name) . '_id';
return $this->relation->hasOne($model, $foreignKey, $localKey);
}
@@ -765,7 +766,7 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
{
// 记录当前关联信息
$model = $this->parseModel($model);
$localKey = $localKey ?: $this->pk;
$localKey = $localKey ?: $this->getPk();
$foreignKey = $foreignKey ?: Loader::parseName($this->name) . '_id';
return $this->relation->hasMany($model, $foreignKey, $localKey);
}

View File

@@ -184,7 +184,7 @@ class Merge extends Model
$table = is_int($key) ? self::db()->name($model)->getTable() : $model;
// 处理关联模型数据
$data = $this->parseData($name, $this->data);
self::db()->table($table)->strict(false)->where($this->fk, $this->data[$this->pk])->update($data);
self::db()->table($table)->strict(false)->where($this->fk, $this->data[$this->getPk()])->update($data);
}
// 新增回调
$this->trigger('after_update', $this);
@@ -238,7 +238,7 @@ class Merge extends Model
$result = self::db()->delete($this->data);
if ($result) {
// 获取主键数据
$pk = $this->data[$this->pk];
$pk = $this->data[$this->getPk()];
// 删除关联数据
foreach (static::$relationModel as $key => $model) {