在正常业务场景中,会出现重复出现一个Model 被 curd 多次的情况,但是,如果不处理之前已经使用的模型对象则会报错,
文档中暂时没找到初始化已经被构建过的模型对象,看过model 类 (在源码 src/Illuminate/Database/Eloquent/Model.php)下
有三个公告方法可用
1. newQuery 方法
/**
* Get a new query builder for the model's table.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function newQuery()
{
$builder = $this->newQueryWithoutScopes();
return $this->applyGlobalScopes($builder);
}
2. newInstance 方法 看英文注释,翻译来其实就是 重新初始化一个模型并且默认不携带任何属性,就相当于一个空的没有任何数据的模型对象
/**
* Create a new instance of the given model.
*
* @param array $attributes
* @param bool $exists
* @return static
*/
public function newInstance($attributes = [], $exists = false)
{
// This method just provides a convenient way for us to generate fresh model
// instances of this current model. It is particularly useful during the
// hydration of new objects via the Eloquent query builder instances.
$model = new static((array) $attributes);
$model->exists = $exists;
return $model;
}
3、创建一个现有模型的新实例,并且可以指定属性数据,和链接db选项
/**
* Create a new model instance that is existing.
*
* @param array $attributes
* @param string|null $connection
* @return static
*/
public function newFromBuilder($attributes = [], $connection = null)
{
$model = $this->newInstance([], true);
$model->setRawAttributes((array) $attributes, true);
$model->setConnection($connection ?: $this->connection);
return $model;
}