Laravel中tosql()是如何返回sql


前言

1. laravel version 5.5 

2. 關鍵字sql解析的代碼,我就不上了。有興趣的童鞋,可以去Illuminate\Database\Query\Grammars\Grammar觀望,我也就簡單說下,Laravel的主體思路。

源碼

首先找到tosql()方法所在的位置,Illuminate\Database\Query\Builder:
/** * Get the SQL representation of the query. * * @return string */
    public function toSql() { return $this->grammar->compileSelect($this); }

接着,去 Illuminate\Database\Query\Grammars\Grammar

/**
     * The components that make up a select clause.
     *  關鍵字數組,用於下面的根據對應關鍵字拼接對應方法
     * @var array
     */
    protected $selectComponents = [
        'aggregate',
        'columns',
        'from',
        'joins',
        'wheres',
        'groups',
        'havings',
        'orders',
        'limit',
        'offset',
        'unions',
        'lock',
    ];

 

 /** * Compile a select query into SQL. * * @param \Illuminate\Database\Query\Builder $query * @return string */
    public function compileSelect(Builder $query) { // If the query does not have any columns set, we'll set the columns to the // * character to just get all of the columns from the database. Then we // can build the query and concatenate all the pieces together as one.
        $original = $query->columns; if (is_null($query->columns)) { $query->columns = ['*']; } // To compile the query, we'll spin through each component of the query and // see if that component exists. If it does we'll just call the compiler // function for the component which is responsible for making the SQL.
     // 然鵝,最主體的方法就在這里。
$sql = trim($this->concatenate( $this->compileComponents($query)) ); $query->columns = $original; return $sql; }
    
 /** * Concatenate an array of segments, removing empties. * * @param array $segments * @return string */
    protected function concatenate($segments) {
     // 將空值過濾,並且轉換為一個字符串,返回。(也就是最終返回的sql)
return implode(' ', array_filter($segments, function ($value) { return (string) $value !== ''; })); }
/** * Compile the components necessary for a select clause. * * @param \Illuminate\Database\Query\Builder $query * @return array */
    protected function compileComponents(Builder $query) { $sql = [];      // laravel 會根據sql的關鍵字,for循環出一個sql數組 foreach ($this->selectComponents as $component) { // To compile the query, we'll spin through each component of the query and // see if that component exists. If it does we'll just call the compiler // function for the component which is responsible for making the SQL.
            if (! is_null($query->$component)) { $method = 'compile'.ucfirst($component); $sql[$component] = $this->$method($query, $query->$component); } } return $sql;  }

 

總結

我個人也就是,簡略的通過表象的源碼分析下laravle的toSql()如何返回sql而已,尚未研究更為深透。

為什么開個博文來記錄呢?因為,最近一直在看laravel的源碼,覺得這種思想真的很新穎!!!

共勉~~~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM