laravel5.1框架model类查询的实现方法

laravel框架model类查询实现:

User::where(['uid'=8])->get();

User类继承自Model类:Illuminate\Database\Eloquent\Model

当User类静态调用where方法时,自动调用了Model里的魔术方法:

public static function __callStatic($method, $parameters)
{
  $instance = new static; //这里的$instance就是User类的实例对象

  return call_user_func_array([$instance, $method], $parameters);
}

相当于调用了user对象的where方法,这时就又调用了魔术方法:

public function __call($method, $parameters)
{
  if (in_array($method, ['increment', 'decrement'])) {
    return call_user_func_array([$this, $method], $parameters);
  }

  $query = $this->newQuery(); //返回Illuminate\Database\Eloquent\Builder对象

  return call_user_func_array([$query, $method], $parameters);
}

相当于调用Illuminate\Database\Eloquent\Builder对象里的where方法和get方法,这两个方法里其实

其实是封装调用了Illuminate\Database\Query\Builder对象里的where方法和get方法->get方法里调用了runselect方法

runSelect方法:

/**
 * Run the query as a "select" statement against the connection.
 *
 * @return array
 */
protected function runSelect()
{
  return $this->connection->select($this->toSql(), $this->getBindings(), ! $this->useWritePdo); //调用connection 对象的select方法
}

再看connection对象是怎么传到Illuminate\Database\Eloquent\Builder类实例里的:

Model类的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);
}

Model类的newQueryWithoutScopes方法:

/**
 * Get a new query builder that doesn't have any global scopes.
 *
 * @return \Illuminate\Database\Eloquent\Builder|static
 */
public function newQueryWithoutScopes()
{
  $builder = $this->newEloquentBuilder(
    $this->newBaseQueryBuilder() //这个方法返回
  );

  // Once we have the query builders, we will set the model instances so the
  // builder can easily access any information it may need from the model
  // while it is constructing and executing various queries against it.
  return $builder->setModel($this)->with($this->with);
}

Model类的newBaseQueryBuilder方法实现

/**
 * Get a new query builder instance for the connection.
 *
 * @return \Illuminate\Database\Query\Builder
 */
protected function newBaseQueryBuilder()
{
  $conn = $this->getConnection(); \\连接数据库并返回connection对象

  $grammar = $conn->getQueryGrammar();

  return new QueryBuilder($conn, $grammar, $conn->getPostProcessor()); //Illuminate\Database\Query\Builder

}

      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/4928.html