protected function wrapValue($value)
{
if ($value !== '*') {
return '"'.str_replace('"', '""', $value).'"';
}
return $value;
}
如果参数为*则直接返回了拼接星号的字符串,反之则直接返回了$value数组。然后视线调回collection对象的map方法,返回值在通过array_combine函数加工后,又通过collection本类包装成了对象返回。到这里函数调用就到顶了,依次返回值,返回到Grammars对象的compileColumns方法中,与'select'字符串进行拼接后再次返回。这部分sql语句片段就构建完成了。
protected function compileFrom(Builder $query, $table)
{
return 'from '.$this->wrapTable($table);
}
public function wrapTable($table)
{
if (! $this->isExpression($table)) {
return $this->wrap($this->tablePrefix.$table, true);
}
return $this->getValue($table);
}
from语句的构建比较简单,直接from接表名就好。但是wrapTable方法中的代码我们发现有点眼熟,没错,它又调用了wrap方法,还记得我们刚刚构建select时看到的吗?这个方法只是对传入的参数做了解析,并包装成集合返回回来。其实不止select和from其他的语句段构建都要通过wrap方法来进行参数解析。刚刚已经解析过wrap方法,这里我就不多说了。最后,这个方法也是返回了'from'部分的sql语句片段。
protected function compileWheres(Builder $query)
{
// Each type of where clauses has its own compiler function which is responsible
// for actually creating the where clauses SQL. This helps keep the code nice
// and maintainable since each clause has a very small method that it uses.
if (is_null($query->wheres)) {
return '';
}
// If we actually have some where clauses, we will strip off the first boolean
// operator, which is added by the query builders for convenience so we can
// avoid checking for the first clauses in each of the compilers methods.
if (count($sql = $this->compileWheresToArray($query)) > 0) {
return $this->concatenateWhereClauses($query, $sql);
}
return '';
}
protected function compileWheresToArray($query)
{
return collect($query->wheres)->map(function ($where) use ($query) {
return $where['boolean'].' '.$this->{"where{$where['type']}"}($query, $where);
})->all();
}
protected function concatenateWhereClauses($query, $sql)
{
$conjunction = $query instanceof JoinClause ? 'on' : 'where';
return $conjunction.' '.$this->removeLeadingBoolean(implode(' ', $sql));
}
protected function removeLeadingBoolean($value)
{
return preg_replace('/and |or /i', '', $value, 1);
}
那么,来看一下。首先compileWheres方法判断where条件是否为空,然后compileWheresToArray方法来判断where参数是否大于0。这个方法用了collect对象的map方法,我们之前已经看过了。重要的是这个闭包函数,来看一下这个闭包函数干了什么。它通过$hwere['type']这个属性中存储的字段作为方法名调用了whereBasic方法,如下所示
protected function whereBasic(Builder $query, $where)
{
$value = $this->parameter($where['value']);
return $this->wrap($where['column']).' '.$where['operator'].' '.$value;
}
public function parameter($value)
{
return $this->isExpression($value) ? $this->getValue($value) : '?';
}
通过parameter方法获取到参数后,依然是通过wrap包装参数。concatenateWhereClauses方法根据之前返回的参数,决定拼接'where'字符串,然后通过removeLeadingBoolean方法决定‘and‘等条件的拼接。