iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 29
0
Software Development

30天快速上手Laravel系列 第 29

Day29-[DB 操作] Eloquent ORM 基本操作

取回集合(Aggregates)

另外補充一點Query Builder沒提到的聚合部分,其中Query Builder其實有提供聚合的methods,這樣要取得一些數值的結果就會比較方便,底下附上範例:

//取得Flight active = 1的筆數
$count = App\Flight::where('active', 1)->count();

//取得Flight active = 1的最大price
$maxPrice = App\Flight::where('active', 1)->max('price');

建立資料

public function store($name)
{
    //取得Flight model instance以後把name值賦予到他的name屬性上面
    $flight = new Flight;
    $flight->name = $name;
    $flight->save();
}

created_at 跟updated_at會預設被自動加上,
不用手動設定

更新資料

有兩種方法,第一種是一樣用save,先用find取回model以後寫入(updated_at一樣會被自動更新),第二種是在查詢條件以後直接用update更新

save

$flight = App\Flight::find(1);
$flight->name = 'New Flight Name';
$flight->save();

update

預期接收的型態為array,[欄位 => 要更改的值]

App\Flight::where('active', 1)
          ->where('destination', 'San Diego')
          ->update(['delayed' => 1]);

When issuing a mass update via Eloquent, the saved and updated model events will not be fired for the updated models. This is because the models are never actually retrieved when issuing a mass update.

批量分配

還記得第12章我們介紹過Entities的設定方式嗎? 當我們設定好fillable/guarded以後,就可以開始使用批量處理了。

$flight = App\Flight::create(['name' => 'Flight 10']);

這邊補充一下如果要批量更新,可以用update,但是如果要批量新增的話,目前只能用query builder的insert

firstOrCreate / firstOrNew

// 如果在資料庫找不到模型,會用給定的屬性來新增一筆記錄
$flight = App\Flight::firstOrCreate(
    ['name' => 'Flight 10'], ['delayed' => 1]
);

// 假設找不到模型,將會回傳一個新的模型實例,但需要呼叫save來儲存
$flight = App\Flight::firstOrNew(
    ['name' => 'Flight 10'], ['delayed' => 1]
);

updateOrCreate

如果有找到資料的話就更新,沒有的話就建立一筆資料

// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
    ['departure' => 'Oakland', 'destination' => 'San Diego'],
    ['price' => 99]
);

刪除資料

有三種方法可以刪除資料

//取得model以後在用delete
$flight = App\Flight::find(1);
$flight->delete();

//如果知道PK的話直接不取回model刪除
App\Flight::destroy(1);
App\Flight::destroy(1, 2, 3);
App\Flight::destroy([1, 2, 3]);
App\Flight::destroy(collect([1, 2, 3]));

//Query 的時候刪除
$deletedRows = App\Flight::where('active', 0)->delete();

When executing a mass delete statement via Eloquent, the deleting and deleted model events will not be fired for the deleted models. This is because the models are never actually retrieved when executing the delete statement.

Soft Delete

soft delete的意思就是資料並不是真的刪除,而是利用deleted_at的欄位紀錄資料被刪除了,所以去db找還是可以找到資料。這個我們在第12章的時候也有提到設定方式,設定好deleted_atSoftDelete trait以後就可以開始使用,可以參考第8章的範例。

trash 相關

trashed

檢查指定的model instance是否被soft deleted

if ($flight->trashed()) {
    //
}

withTrashed

取得被刪除的資料

因為query出來的資料會自動排除deleted_at有設定值的欄位,所以要取出來要特別用這個方法。

//使用在query
$flights = App\Flight::withTrashed()
                ->where('account_id', 1)
                ->get();

//使用在relation
$flight->history()->withTrashed()->get();

onlyTrashed

取回被刪除的資料

$flights = App\Flight::onlyTrashed()
                ->where('airline_id', 1)
                ->get();

restore

可以復原soft delete的資料

//單一model restore
$flight->restore();

//一次restore條件底下的models
App\Flight::withTrashed()
        ->where('airline_id', 1)
        ->restore();

//relation也可以被restore
$flight->history()->restore();

forceDelete

永久刪除資料

// 強迫刪除單一的 model instance...
$flight->forceDelete();

// 強迫刪除所有相關的 models...
$flight->history()->forceDelete();

結論: 為什麼要介紹Query Builder又有EloquentModel,除了因為這是laravel一個很方便的功能以外其實也是有效能問題,Eloquent Model 是經過laravel包裝後有做一些處理會比較慢,而且有些動作也還是沒有支援,所以如果是一般基礎的操作可以,但是如果request time 很長就可以考慮用Query Builder,另外如果是比較複雜的指令,之前提到的DB::statement用法還是會拿出來使用。

參考連結:


上一篇
Day 28-[DB 操作] Eloquent ORM 取回資料
下一篇
Day30-[Others] 感言與其他補充
系列文
30天快速上手Laravel30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言