Model类field方法更名为allowField,增加saveAll方法批量新增数据

改进一对一的关联新增
This commit is contained in:
thinkphp
2016-04-19 22:16:28 +08:00
parent 1e1d2ab951
commit aa585a60b2
2 changed files with 24 additions and 3 deletions

View File

@@ -411,13 +411,27 @@ abstract class Model implements \JsonSerializable, \ArrayAccess
return $result; return $result;
} }
/**
* 保存多个数据到当前数据对象
* @access public
* @param array $data 数据
* @return integer
*/
public function saveAll($dataSet)
{
foreach ($dataSet as $data) {
$result = $this->save($data);
}
return $result;
}
/** /**
* 设置允许写入的字段 * 设置允许写入的字段
* @access public * @access public
* @param bool $update * @param bool $update
* @return $this * @return $this
*/ */
public function field($field) public function allowField($field)
{ {
$this->field = $field; $this->field = $field;
return $this; return $this;

View File

@@ -73,6 +73,13 @@ class Relation
case self::HAS_ONE: case self::HAS_ONE:
case self::BELONGS_TO: case self::BELONGS_TO:
$result = $db->find(); $result = $db->find();
if (false === $result) {
$class = $this->model;
$result = new $class;
$foreignKey = $this->foreignKey;
$localKey = $this->localKey;
$result->$foreignKey = $this->parent->$localKey;
}
break; break;
case self::HAS_MANY: case self::HAS_MANY:
case self::BELONGS_TO_MANY: case self::BELONGS_TO_MANY:
@@ -240,7 +247,7 @@ class Relation
// 重新组装模型数据 // 重新组装模型数据
foreach ($result->toArray() as $key => $val) { foreach ($result->toArray() as $key => $val) {
if (strpos($key, '__')) { if (strpos($key, '__')) {
list($name, $attr) = explode('__', $key,2); list($name, $attr) = explode('__', $key, 2);
if ($name == $modelName) { if ($name == $modelName) {
$list[$name][$attr] = $val; $list[$name][$attr] = $val;
unset($result->$key); unset($result->$key);
@@ -300,7 +307,7 @@ class Relation
$pivot = []; $pivot = [];
foreach ($set->toArray() as $key => $val) { foreach ($set->toArray() as $key => $val) {
if (strpos($key, '__')) { if (strpos($key, '__')) {
list($name, $attr) = explode('__', $key,2); list($name, $attr) = explode('__', $key, 2);
if ('pivot' == $name) { if ('pivot' == $name) {
$pivot[$attr] = $val; $pivot[$attr] = $val;
unset($set->$key); unset($set->$key);