mysql - Laravel Eager Loading 两端都有一些 where 条件
问题描述
我得到这样的sql查询:
select * from
geofilter_activations
where not exists (select * fromsnap_submissions
wheregeofilter_activations
.purchase_id
=snap_submissions
.purchase_id
) andstatus
= 0 andcreated_at
< 2018-10-10 07:15:42 order byid
desc 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');
}
}
解决方案
也许这些方面的东西可以帮助你:
$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
因为您在需要时请求对象。
推荐阅读
- javascript - 从反应中的一组对象计算发票总额和发票数量
- stripe-payments - 条带结帐测试返回 404
- c++ - 关于在赋值中从 double 到 int 的隐式转换的标准
- javascript - 如何从我点击的元素中选择内容(使用数据属性)
- xml - 是否有任何用于 Spark 的 XML 输入的模式生成器?
- javascript - 在弹出式灯箱中更新 Swiper
- javascript - 如何在 React 中使用 ref 访问 onDrag onDrop 函数?
- javascript - 无法从 fetch 中输出数据
- c - SAME70 在 ISR 中读取外部中断极性
- java - 如何将带有列表视图的 EditText 滚动到片段中布局的最顶部?