一對一關(guān)系:
A與B的關(guān)系:? ? A(id) =B(a_id)
在主表A中加入方法b():return ?$this->hasOne('B');
在子表B中加入方法a():return? $this->belongsTo('A');
一對多關(guān)系:
A與B的關(guān)系:? ? A(id) =B(a_id)
在主表A中加入方法b():return$this->hasMany('B');
在子表B中加入方法a():return? $this->belongsTo('A');
多對多關(guān)系:
A(id) ?B(id) ?C(a_id,b_id)
在主表A中加入方法bs():return? $this->belongsToMany('B')->withPivot();
在子表B中加入方法as():return? $this->belongsToMany('A');
一對多再對多關(guān)系:
A有n個B,每個B有n個C,求A有多少C;
在主表A中加入方法cs():return ?$this->hasManyThrough('C','B');
多態(tài)關(guān)系:
A(id) B(id) C(id,x_id,x_type)
A 表:c() :$this->morphMany('C','x');
B 表:c() :$this->morphMany('C','x');
C 表:x() :$this->morphTo();
查詢關(guān)系存在性:
A(id) ?B(a_id)
至少有一個B :has('bs')
存在where的B:whereHas('bs',function($query){ ? ??$query->where(); ? })
預(yù)加載與A有關(guān)系的所有B: A::with('b');
帶where的預(yù)加載:whth([ ?'b'=>function($query){ ? ?$query->where(); ? } ? ]);
延遲(獲取A數(shù)據(jù)后再預(yù)加載B)$a->load(b);
save() : 保存模型實(shí)例;
create() : 保存數(shù)組;
多對多關(guān)系的操作:
添加新B : attach($bid,['b_name'=>'name']);
刪除某B:detach($id); ? ?所有 detach();
更新中間表:updateExistingPivot($bid,['name'=>'name']);
同步關(guān)聯(lián)(校準(zhǔn)):$a->bs()->sync(1,2,3);
更新子表,父ID的updated_at也會更新:$touches=['post'];
本地約束查詢:scopeA(); ?調(diào)用 ?A::A()->get();
模型轉(zhuǎn)數(shù)組:$a->toArray();
模型轉(zhuǎn)json : $a->toJson();
加一些數(shù)據(jù)庫不存在的值或自動改變字段:model中加 getXXXAttribute();(此方法自動加載)
自動修改某字段后保存:setXXXAttribute();
以上兩種方法類似:$casts=['key'=>'needType'];
參考:https://laravel-china.org/articles/3818