繁体   English   中英

Laravel渴望在两端都有条件的情况下加载

[英]Laravel Eager Loading with some where conditions in both ends

我正在这样的SQL查询:

SELECT * FROM geofilter_activations其中不存在(SELECT * FROM snap_submissions其中geofilter_activationspurchase_id = snap_submissionspurchase_id )和status = 0和created_at <2018年10月10日7时15分42秒以便通过id降序极限1

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

    $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');
    }
}

也许这些思路可以帮助您:

$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 ,因此必须使用with查询中的关系。 上面提到的带有负载的示例实际上是lazy load因为您在需要时请求一个对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM