我在Laravel eloquent中遇到了我的查询问题,当我运行查询时,我没有得到结果,生成的查询似乎不是我所期望的.
这是控制器中的代码:
$lastUpdate = Input::get('last_update');
$userId = Auth::user()->id;
$eventIds = EventVendor::where('user_id', $userId)
->where('is_active', 1)->get()->lists('event_id');
$events = EventDetails::whereIn('id', $eventIds)
->where(function($query) use ($lastUpdate) {
$query->where('created_at', $lastUpdate);
$query->orWhere('updated_at', $lastUpdate);
})
->where('is_active', 1)
->with("details_sub")
->with("extras")
->with("chargesDiscounts")
->toSql();
这是生成的查询:
select * from `mtgh_event_details`
where `mtgh_event_details`.`deleted_at` is null
and 0 = 1
and (`created_at` = ? or `updated_at` = ?)
and `is_active` = ?
除了0 = 1,它不应该在那里,我也没有看到完整的查询.
解决方法:
0 = 1正在显示,因为填充$eventIds的查询未返回任何结果,因此您的Collection为空.如果将空数组(或Collection)传递给whereIn(),它会通过添加0 = 1来快速查询查询,因为搜索()中的id是无效SQL,并且在空集中进行逻辑搜索将始终不返回任何结果.此快捷方式已添加到4.2.17和this pull request中.
至于查询的其余部分,一切看起来都很正常. with()语句正在设置eager loading,它使用单独的SQL语句;它不使用连接.
因此,由于您有三个with()语句,您实际上将运行四个单独的查询,一个用于获取EventDetails,然后一个用于加载您的details_sub,extras和chargesDiscounts以用于加载的事件详细信息.
由于它们是单独的查询,因此它们不会显示在toSql()输出中.
其他说明:
>获取事件ID时,您无需调用 – > get() – > lists(),您只需在查询上调用 – > lists()即可.如果先调用get(),它会将完整的对象加载到Collection中,然后在Collection上调用lists().只需在查询本身上调用lists(),就可以避免首先加载完整的Collection.
>假设您已设置关系,则可以避免初始查询首先获取ID.您可以使用whereHas()
method代替.您的查询将如下所示:
$lastUpdate = Input::get('last_update');
$userId = Auth::user()->id;
// assumes a relationship named 'vendor'
$events = EventDetails::whereHas('vendor', function($query) use ($userId) {
// $query is query for the EventVendors
$query->where('user_id', $userId)->where('is_active', 1)
})
->where(function($query) use ($lastUpdate) {
$query->where('created_at', $lastUpdate);
$query->orWhere('updated_at', $lastUpdate);
})
->where('is_active', 1)
->with("details_sub")
->with("extras")
->with("chargesDiscounts")
->toSql();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。