gpt4 book ai didi

php - Laravel 中的高级 Where 子句

转载 作者:可可西里 更新时间:2023-11-01 00:41:16 25 4
gpt4 key购买 nike

我在 Laravel Eloquent 中的查询有问题,我在运行查询时没有得到结果,而且生成的查询似乎不是我所期望的。

这是 Controller 中的代码:

$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 来简化查询,因为搜索 where id in () 是无效的 SQL,逻辑上在一个空集合中搜索总是不会返回任何结果。此快捷方式是在 4.2.17 中添加的 this pull request .

至于查询的其余部分,我觉得一切正常。 with() 语句正在设置预加载,它使用单独的 SQL 语句;它不使用联接。

因此,由于您有三个 with() 语句,您实际上将运行四个独立的查询,一个用于获取您的 EventDetails,然后每个用于加载您的details_subextraschargesDiscounts 加载的事件详细信息。

因为它们是单独的查询,所以它们不会出现在 toSql() 输出中。


其他说明:

  • 获取事件id时,不需要调用->get()->lists(),直接调用->lists() 在查询上。如果您先调用 get(),它会将完整的对象加载到一个 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();

关于php - Laravel 中的高级 Where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36389008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com