欧美亚洲中文,在线国自产视频,欧洲一区在线观看视频,亚洲综合中文字幕在线观看

      1. <dfn id="rfwes"></dfn>
          <object id="rfwes"></object>
        1. 站長資訊網(wǎng)
          最全最豐富的資訊網(wǎng)站

          Laravel 中如何對 ORM 實現(xiàn)理解

          Laravel 中如何對 ORM 實現(xiàn)理解

          什么叫ORM

          ORM,全稱 Object-Relational Mapping(對象關系映射),它的作用是在關系型數(shù)據(jù)庫和業(yè)務實體對象之間作一個映射, 這樣,我們在操作具體的業(yè)務對象時,就不需要再去和復雜的SQL語句打交道,只需簡單的操作對象的屬性和方法即可。

          ORM 實現(xiàn)方式

          兩種最常見的實現(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 中的難點 也就理解了,我們來看一下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)用者的實例, new self() 返回的是自身實例
          使用eloqument 查詢的時候

          $list = Politician::where('party_id', 1)->count();

          where 方法不在 Model中 會先執(zhí)行callStatic()函數(shù) 獲取 AppModelsPolitician 實例 ,再執(zhí)行 call() , 在$this->newQuery() 返回實例中尋找where() count()等方法。
          細看一下 newQuery() 方法 這里面返回的實例。 理解了這兩個魔術函數(shù) 對laravel 中 orm的實現(xiàn)的難點就攻克了。

          laravel 中的查詢構造器

          $list = DB::table('categoty')->get();

          Eloquent ORM 實際上是對 查詢構造進行了一次封裝,可以更方便的去操作。 查詢構造器的源碼大家有興趣的話可以看一看,謝謝。

          相關學習推薦:Laravel

          贊(0)
          分享到: 更多 (0)
          網(wǎng)站地圖   滬ICP備18035694號-2    滬公網(wǎng)安備31011702889846號