簡體   English   中英

laravel Eloquent 有和沒有實例

[英]laravel Eloquent with and without an instance

我是Laravel的新手。

我想知道兩者的區別

  1. 實例化 Model class。
 $example = new modelClass();
 $example->first();

  1. 無需實例化 Model Class。
  $example = ModelClass::all();

誰能幫忙。 謝謝。

不同之處在於,當您使用new運算符時,您會得到一個 model class 的實例,其中包含所有可用的方法,但屬性為空。 When you calling first() method of this empty model instance, since Eloquent is active record ORM, Model class makes it's magic, calling sql, filling the properties and returns you same model but with not empty properties already.

Meanwhile, when you use model class as facade for you'r operation, system again resolves entity of model class under the hood, and then calling all method of same initialized object, like int first example, but all method returns not model instance, it返回模型集合 - 使用類似數組的 object,因此您可以遍歷,但有一堆附加功能。

所以,如果你想知道調用外觀和初始化 object 有什么區別,沒有區別,除了系統會為你初始化 object,但是如果你正在尋找靈活的系統,你會意識到使用外觀,因為要調用外觀,您應該直接調用 class,而不是抽象,而對於 model,您可以創建工廠實例並將其稱為抽象。

但是,對於新的,您可以使用外牆,但是當您將北斗挖入 OOP 時,請記住以上內容!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM