
ORM,全稱 Object-Relational Mapping(對象關(guān)系映射),它的作用是在關(guān)系型數(shù)據(jù)庫和業(yè)務(wù)實(shí)體對象之間作一個映射, 這樣,我們在操作具體的業(yè)務(wù)對象時,就不需要再去和復(fù)雜的SQL語句打交道,只需簡單的操作對象的屬性和方法即可。ORM 實(shí)現(xiàn)方式
兩種最常見的實(shí)現(xiàn)方式是 ActiveRecord 和 DataMapper (laravel 中使用的是前者)我們先來理解兩個魔法函數(shù) __call() 和 __callStatic()
class Test{
//動態(tài)調(diào)用的時候 沒有找到此函數(shù) 則執(zhí)行__call() 方法
public function __call($method, $parameters){
echo 22222222222;
return (new Rest)->$method(...$parameters);
}
//靜態(tài)調(diào)用的時候 沒有找到此函數(shù) 則執(zhí)行__callStatic()方法
public static function __callStatic($method, $parameters){
echo 1111111111;
return (new static)->$method(...$parameters);
}}class Rest{
public function foo($name , $age){
echo 333;
dump($name,$age);
}}
//先調(diào)用了__callStatic(), 在調(diào)用__call(), 然后調(diào)用 foo();
Test::foo('張三',17);
//只調(diào)用了 __call(), 然后調(diào)用 foo();
(new Test())->foo('李四',16);die;理解了前面兩個魔法函數(shù) 對于laravel Eloqument ORM 中的難點(diǎn) 也就理解了,我們來看一下Model中的源碼
/**
* Handle dynamic method calls into the model. * * @param string $method
* @param array $parameters
* @return mixed
*/public function __call($method, $parameters){
if (in_array($method, ['increment', 'decrement'])) {
return $this->$method(...$parameters);
}
return $this->newQuery()->$method(...$parameters);}
/**
* Handle dynamic static method calls into the method. * * @param string $method
* @param array $parameters
* @return mixed
*/public static function __callStatic($method, $parameters)
{
return (new static)->$method(...$parameters);
}new static 返回的是調(diào)用者的實(shí)例, new self() 返回的是自身實(shí)例
使用eloqument 查詢的時候
$list = Politician::where('party_id', 1)->count();where 方法不在 Model中 會先執(zhí)行callStatic()函數(shù) 獲取 App\\Models\\Politician 實(shí)例 ,再執(zhí)行 call() , 在$this->newQuery() 返回實(shí)例中尋找where() count()等方法。
細(xì)看一下 newQuery() 方法 這里面返回的實(shí)例。 理解了這兩個魔術(shù)函數(shù) 對laravel 中 orm的實(shí)現(xiàn)的難點(diǎn)就攻克了。
$list = DB::table('categoty')->get();Eloquent ORM 實(shí)際上是對 查詢構(gòu)造進(jìn)行了一次封裝,可以更方便的去操作。 查詢構(gòu)造器的源碼大家有興趣的話可以看一看,謝謝。
相關(guān)學(xué)習(xí)推薦:Laravel
當(dāng)前標(biāo)題:Laravel中如何對ORM實(shí)現(xiàn)理解
文章位置:http://chinadenli.net/article20/cgpgco.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、企業(yè)建站、微信小程序、電子商務(wù)、網(wǎng)站營銷、虛擬主機(jī)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)