首页 > 解决方案 > Laravel Eager Loading 两端都有一些 where 条件

问题描述

我得到这样的sql查询:

select * from geofilter_activationswhere not exists (select * from snap_submissionswhere geofilter_activations. purchase_id= snap_submissions. purchase_id) and status= 0 and created_at< 2018-10-10 07:15:42 order by iddesc limit 1

但是我添加了 wherenotnull 的 subscription_id 的查询发生了什么?它没有出现在查询输出中。给我一种优化查询并使其工作的方法。

    $time_before = '10';
    $dt = Carbon::now();

    $activation = GeofilterActivation::doesntHave('submission_data')
        ->where('status', '0')
        ->where('created_at', '<', $dt->subMinutes($time_before)->toDateTimeString())
        ->OrderBy('id','desc')
        ->first();

    $activation->load(['purchase' => function ($query) {
        $query->whereNotNull('subscription_id');
    }]);

GeoFilterActivation 模型是:

<?php

namespace App\Models\Geofilter;

use Illuminate\Database\Eloquent\Model;

class GeofilterActivation extends Model
{
    public function purchase(){
        return $this->belongsTo('App\Models\Geofilter\GeofilterPurchase', 'purchase_id');
    }
    public function submission_data(){
        return $this->belongsTo('App\Models\Geofilter\SnapSubmission', 'purchase_id', 'purchase_id');
    }

    public function ad_stat(){
        return $this->belongsTo('App\Models\Geofilter\SnapAdStat', 'purchase_id', 'purchase_id');
    }

    public function currency(){
        return $this->belongsTo('App\Models\Currency', 'currency_code', 'code');
    }
}

标签: mysqllaravellaravel-5eloquent

解决方案


也许这些方面的东西可以帮助你:

$result = GeofilterActivation::with(['purchase' => function($query) {
        $query->whereNotNull('subscription_id');
    }])
    ->doesntHave('submission_data')
    ->where('status','0')
    ->where('created_at', '<', $dt->subMinutes($time_before)->toDateTimeString())
    ->OrderBy('id','desc')
    ->first();

您的查询不包含它load的原因是因为load在您的查询执行后调用,因此您必须在查询中包含关系 using with。您上面提到的负载示例实际上是lazy load因为您在需要时请求对象。


推荐阅读