Builder::select
源碼
public function select($columns = ['*'])
{
$this -> columns = is_array($columns) ? $columns : func_get_args();
//設(shè)置被選擇的字段
//如果被選擇的字段是一個數(shù)組,那么設(shè)置當(dāng)前query的clumns為這個數(shù)組
//如果被選擇的字段不是一個數(shù)組,用func_get_args把這些參數(shù)變成一個數(shù)組
return $this;
}
示例
$builder = User::where("id", 160124) -> select("id", "realname", "nickname");
$builder = User::where("id", 160124) -> select(["id", "realname", "nickname"]);
dump($builder->get());
代碼分析
首先讓我感到疑惑的是,為什么函數(shù)的形參可以和傳遞過來的實(shí)參不一一對應(yīng)。于是我發(fā)現(xiàn)了func_get_args()的作用。
func_get_args():獲取函數(shù)的所有參數(shù)。
func_get_arg($index):傳遞一個下標(biāo),可以獲得參數(shù)列表中對應(yīng)的參數(shù)。
func_num_args():獲取函數(shù)參數(shù)的個數(shù)。
function foo(){
$args_num = func_num_args();
echo "Number of arguments: $args_num<br/>\n";
$args_list = func_get_args();
for ($i =0; $i < $args_num; $i++) {
echo "Argument $i is: ".func_get_arg($i)."<br/>";
}
}
foo(1,2,3);
輸出
Number of arguments: 3
Argument 0 is: 1
Argument 1 is: 2
Argument 2 is: 3
Builder::addSelct,Builder::selectRaw
兩個函數(shù)具有相同作用
源碼
public function addSelect($column)
{
//往被選擇的字段添加字段,即擴(kuò)充被選擇字段
//參數(shù)支持?jǐn)?shù)組和多個字符串
$column = is_array($column) ? $column : func_get_args();
$this->columns = array_merge((array) $this->columns, $column);
return $this;
}
示例
$builder = User::where("id", "160124") ->select("id", "realname") -> selectRaw("nickname");
$builder = User::where("id", "160124") ->select(["id"]) -> addSelect(["nickname", "realname"]);
dump($builder->get());
selectSub
完全看不懂在說什么,o(╯□╰)o,可以參考以下信息。
StackOverFlow參考
distinct
據(jù)說是去重,但是不知道怎么用。
源碼
public function distinct(){
//Force the query to only return distinct results.
$this->distinct = true;
return $this;
}
在Laravel中想要針對某個字段去重可以使用unique。
unique方法返回集合中所有的唯一數(shù)據(jù)項:
$collection = collect([1, 1, 2, 2, 3, 4, 2]);
$unique = $collection->unique();
$unique->values()->all();
// [1, 2, 3, 4]
返回的集合保持原來的數(shù)組鍵,在本例中我們使用values方法重置這些鍵為連續(xù)的數(shù)字索引。
處理嵌套數(shù)組或?qū)ο髸r,可以指定用于判斷唯一的鍵:
$collection = collect([
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'iPhone 5', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]);
$unique = $collection->unique('brand');
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
]
*/
你還可以指定自己的回調(diào)用于判斷數(shù)據(jù)項唯一性:
$unique = $collection->unique(function ($item) {
return $item['brand'].$item['type'];
});
$unique->values()->all();
/*
[
['name' => 'iPhone 6', 'brand' => 'Apple', 'type' => 'phone'],
['name' => 'Apple Watch', 'brand' => 'Apple', 'type' => 'watch'],
['name' => 'Galaxy S6', 'brand' => 'Samsung', 'type' => 'phone'],
['name' => 'Galaxy Gear', 'brand' => 'Samsung', 'type' => 'watch'],
]
*/