1. 程式人生 > >Laravel之Eloquent ORM

Laravel之Eloquent ORM

一、ORM程式設計思想

1.1 Active Record 設計模式

 

    Active Record 是一種資料訪問設計模式,它可以幫助你實現資料物件Object到關係資料庫的對映。應用Active Record時,每一個類的例項物件唯一對應一個數據庫表的一行(一對一關係)。你只需繼承一個abstract Active Record 類就可以使用該設計模式訪問資料庫,其最大的好處是使用非常簡單

 

 

1.2 除錯工具 Laravel Debugbar

 

Installation:

composer require barryvdh/laravel-debugbar --dev

二、一對一關係對映

2.1 建立表

public function up() { Schema::create('profiles', function (Blueprint $table) { $table->increments('id'); $table->string('phone'); $table->unsignedInteger('user_id'); //顯示的宣告外來鍵:通知資料庫根據外來鍵關聯表和建立索引,提高執行速度 $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); $table->timestamps(); }); }

2.2 建立模型關係

2.2.1 正向關係繫結

public function profile() { return $this->hasOne(Profile::class); }

2.2.2 反向關係繫結

public function user() { return $this->belongsTo(User::class); }

2.3 外來鍵

 

自定義外來鍵:

return $this->hasOne(Profile::class,'顯示指定自定義外來鍵'); 

2.4 一對一測試

    依賴注入

Request $request,獲取當前登入使用者$request->user()

Route::get('/test',function (Request $request){
    //反向 // $profile = \App\Profile::find(1); // dd($profile->user); $user = $request->user(); // if (is_null($user->profile)){ // $user->profile()->create([ // 'phone' => '15801340269' // ]); // } //用firstOrCreate改進if $user->profile()->firstOrCreate(['user_id' => $user->id],[ 'phone' => '18363046291' ]); //訪問屬性一樣訪問方法 dd($user->profile); });

三、一對多關係對映

 

1:N hasMany(XXX:class) 反之:belongsTo(XXX:class) 

 

 

3.1 面向物件方式繫結一對多的關係

 

四、多對多關係對映

    中間表命名:按照A-Z首字母排序

public function users() { return $this->belongsToMany(User::class); } public function habits() { return $this->belongsToMany(Habit::class); }

4.1 面向物件方式繫結多對多的關係

 

detach解綁,sync方法用的比較多,只保留1,2

4.2 訪問多對多中間資料表

 

 

 

五、HasManyThrough物件橋接式穿越關聯(遠層一對多)

資料表:

countries
    id - integer
    name - string

users
    id - integer country_id - integer name - string posts id - integer user_id - integer title - string
class Country extends Model { protected $fillable = ['name']; /** * 獲得某個國家下所有的使用者文章。 */ public function papers() { return $this->hasManyThrough(Paper::class,User::class); } }
$factory->define(App\Paper::class, function (Faker $faker) {
    return [
        'title' => $faker->sentence, 'user_id' => \App\User::all()->random()->id, ]; });

 

 

$factory->define(App\User::class, function (Faker $faker) {
    return [
        'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'country_id' => \App\Country::all()->random()->id, 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret 'remember_token' => str_random(10), ]; });

 

獲取每個國家論文總數:

 

五、多樣化的一對多關係對映(多型關聯)

面向物件多型:執行時載入機制

 


偽造資料:

 

六、多對多多型關聯

除了傳統的多型關聯,您也可以定義「多對多」的多型關聯。例如,Post 模型和 Video 模型可以共享一個多型關聯至 Tag 模型。 使用多對多多型關聯可以讓您在文章和視訊中共享唯一的標籤列表。