laravel ORM

关联查询

需求:三张表 合同 账单 账单明细(明细关联账单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问题。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容