關(guān)聯(lián)查詢
需求:三張表 合同 賬單 賬單明細(xì)(明細(xì)關(guān)聯(lián)賬單id,賬單關(guān)聯(lián)合同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中兩個(gè)key的位置 再試試hasMany 和 with能不能實(shí)現(xiàn)
預(yù)加載
場景: 比如 每個(gè)合同有很多賬單 你定義了一個(gè)關(guān)聯(lián),contract hasMany bill

image.png
語句打印出的語句如下

image.png
但是,假如這么寫

image.png
語句是下面這樣

image.png
這就是預(yù)加載,還有所謂的n+1問題。