Featured image of post Day 12. Eloquent: Model

Day 12. Eloquent: Model

資源

Laravel7 30天: 目錄
專案連結: github - laravel7 之 30 天分享

前言

上一篇: Day 11. 建立資料表: Migration
今天來分享 Laravel 的 model 名為 Eloquent ORM

主要

上!文!件!
Eloquent 也是我覺得 Laravel 很香的原因之一,
這邊簡單介紹一下,關聯的部份之後再獨立聊

基本設定

基本設定文件

自定義 Table Name

1
2
3
4
class User extends Model
{
    protected $table = 'user_list';
}

自定義 Primary Keys

1
2
3
4
class User extends Model
{
    protected $primaryKey = 'pid';
}

軟刪除

我們常常會設定軟刪除在大部分的表,因為避免資料刪除後無法回溯問題,
這時候我們就需要在 Model use SoftDeletes; 當然我要還要設定 migration $table->softDeletes();

migration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();  // *** 這個
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

model

1
2
3
4
5
6
7
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
 
class User extends Model
{
    use SoftDeletes; // *** 這個
}

方便的方法們

搜尋 find()

find 可以直接找 Primary Keys

1
User::find(1) 

新增 create()

傳入整個 array

1
2
3
User::create([
    'name' => 'abc'
]);

更新 update()

傳入整個 array

1
2
3
4
$user = User::find(1);
$user->update([
    'name' => 'abc'
]);

直接存 save()

也分以單獨存取最後再 save() 就好。

1
2
3
$user = User::find(1);
$user->name = 'abc';
$user->save();

更新或刪除 updateOrCreate()

顧名思義就是找不到我就新增,找得到我就修改
第一個參數是條件,
第二個參數是值

1
2
3
4
5
User::updateOrCreate([
    'id' => 1,
], [
    'name' => 'abc'
]);

刪除 delete()

1
2
$user = User::find(1);
$user->delete();

常用的條件 Scopes

有些比較常用搜尋條件可以透過這個
Scopes 分成 global 跟 local
我這邊只介紹 local, global 基本上用不到
global Scopes 是全域的概念,每次Query 都會附加上去的 搜尋條件
方法如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class User extends Model
{
    /**
     * Scope a query to only include active users.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }
}

// 使用方法
User::active()->get()
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy