關聯查詢
需求:三張表 合同 賬單 賬單明細(明細關聯賬單id,賬單關聯合同id)
$res = \App\Model\BillDetail::whereHas('getDeposit', function ($query) {
$query->where('contract_order_guid', '3f7242d2d8f911e7afcdafa3cdc44eb6');
})->get();
dd($res);
public function getDeposit()
{
return $this->belongsTo('App\Model\ContractBill', 'bill_guid', 'guid')->where('type', config('status.contract_bill_type_deposit'))->where('status', config('status.bill_detail_able'));
}
注意:whereHas belongsTo 和model中兩個key的位置 再試試hasMany 和 with能不能實現
預加載
場景: 比如 每個合同有很多賬單 你定義了一個關聯,contract hasMany bill
image.png
語句打印出的語句如下
image.png
但是,假如這么寫
image.png
語句是下面這樣
image.png
這就是預加載,還有所謂的n+1問題。