Active Record 是一種數據訪問設計模式,它可以幫助你實現數據對象Object到關系數據庫的映射。應用Active Record時,每一個類的實例對象唯一對應一個數據庫表的一行(一對一關系)。你只需繼承一個abstract Active Record 類就可以使用該設計模式訪問數據庫,其最大的好處是使用非常簡單
https://github.com/barryvdh/l...
Installation:
composer require barryvdh/laravel-debugbar --dev二、一對一關系映射2.1 創建表
html' target='_blank'>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)
中間表命名:按照A-Z首字母排序
public function users() return $this- belongsToMany(User::class);public function habits() return $this- belongsToMany(Habit::class);}4.1 面向對象方式綁定多對多的關系
detach解綁,sync方法用的比較多,只保留1,2
數據表:
countries id - integer name - stringusers id - integer country_id - integer name - stringposts 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.KjNyWgaHb9cbcoQgpFlYg7B77UdFm , // secret remember_token = str_random(10),});
獲取每個國家論文總數:
更多:https://laravel-china.org/doc...
偽造數據:
除了傳統的多態關聯,您也可以定義「多對多」的多態關聯。例如,Post 模型和 Video 模型可以共享一個多態關聯至 Tag 模型。 使用多對多多態關聯可以讓您在文章和視頻中共享唯一的標簽列表。
更多:https://laravel-china.org/doc...
以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP !
相關推薦:
Laravel 5.5中為響應請求提供的可響應接口的詳解
關于Laravel基礎Migrations的解析
以上就是關于Laravel的Eloquent ORM的解析的詳細內容,PHP教程
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答