什么叫ORM
ORM,全稱 Object-Relational Mapping(對(duì)象關(guān)系映射),它的作用是在關(guān)系型數(shù)據(jù)庫(kù)和業(yè)務(wù)實(shí)體對(duì)象之間作一個(gè)映射, 這樣,我們?cè)诓僮骶唧w的業(yè)務(wù)對(duì)象時(shí),就不需要再去和復(fù)雜的SQL語(yǔ)句打交道,只需簡(jiǎn)單的操作對(duì)象的屬性和方法即可。
ORM 實(shí)現(xiàn)方式
兩種最常見(jiàn)的實(shí)現(xiàn)方式是 ActiveRecord 和 DataMapper (laravel 中使用的是前者)
我們先來(lái)理解兩個(gè)魔法函數(shù) __call() 和 __callStatic()
class Test{ //動(dòng)態(tài)調(diào)用的時(shí)候 沒(méi)有找到此函數(shù) 則執(zhí)行__call() 方法 public function __call($method, $parameters){ echo 22222222222; return (new Rest)->$method(...$parameters); } //靜態(tài)調(diào)用的時(shí)候 沒(méi)有找到此函數(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;
理解了前面兩個(gè)魔法函數(shù) 對(duì)于laravel Eloqument ORM 中的難點(diǎn) 也就理解了,我們來(lái)看一下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 查詢的時(shí)候
$list = Politician::where('party_id', 1)->count();
where 方法不在 Model中 會(huì)先執(zhí)行callStatic()函數(shù) 獲取 AppModelsPolitician 實(shí)例 ,再執(zhí)行 call() , 在$this->newQuery() 返回實(shí)例中尋找where() count()等方法。
細(xì)看一下 newQuery() 方法 這里面返回的實(shí)例。 理解了這兩個(gè)魔術(shù)函數(shù) 對(duì)laravel 中 orm的實(shí)現(xiàn)的難點(diǎn)就攻克了。
laravel 中的查詢構(gòu)造器
$list = DB::table('categoty')->get();
Eloquent ORM 實(shí)際上是對(duì) 查詢構(gòu)造進(jìn)行了一次封裝,可以更方便的去操作。 查詢構(gòu)造器的源碼大家有興趣的話可以看一看,謝謝。
相關(guān)學(xué)習(xí)推薦:Laravel