zoukankan      html  css  js  c++  java
  • larval5.1模型静态使用多次出现查询属性信息存在问题

    在正常业务场景中,会出现重复出现一个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;
    }
  • 相关阅读:
    【反射】Java反射机制
    Composer教程之常用命令
    Composer教程之基础用法
    Composer教程之初识Composer
    Composer 的结构详解
    现代 PHP 新特性系列(七) —— 内置的 HTTP 服务器
    现代 PHP 新特性系列(一) —— 命名空间
    现代 PHP 新特性系列(二) —— 善用接口
    现代 PHP 新特性系列(三) —— Trait 概览
    现代 PHP 新特性系列(四) —— 生成器的创建和使用
  • 原文地址:https://www.cnblogs.com/final507/p/15769998.html
Copyright © 2011-2022 走看看