簡體   English   中英

Laravel中的高級條款

[英]Advanced Where Clause In Laravel

我在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來快捷查詢查詢,因為搜索where id in ()是無效SQL,並且在空集中進行邏輯搜索將始終不返回任何結果。 使用此拉取請求在4.2.17中添加了此快捷方式。

至於查詢的其余部分,一切看起來都很正常。 with()語句正在設置eager loading,它使用單獨的SQL語句; 它不使用連接。

因此,由於您有三個with()語句,您實際上將運行四個單獨的查詢,一個用於獲取EventDetails ,然后一個用於加載您的details_subextraschargesDiscounts以用於加載的事件詳細信息。

由於它們是單獨的查詢,因此它們不會顯示在toSql()輸出中。


其他說明:

  • 獲取事件ID時,您不需要調用->get()->lists() ,您只需在查詢上調用->lists() 如果先調用get() ,它會將完整的對象加載到Collection ,然后在Collection上調用lists() 只需在查詢本身上調用lists() ,就可以避免首先加載完整的Collection

  • 假設您已設置關系,則可以避免初始查詢首先獲取ID。 您可以使用whereHas()方法 您的查詢將如下所示:

     $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(); 

所以我發現了這個問題,顯然這是查詢的一部分

$eventIds = EventVendor::where('user_id', $userId)
                    ->where('is_active', 1)->get()->lists('event_id');

返回null或空列表,因此我的查詢中的0 = 1 另外,在另一個答案的幫助下,我能夠簡化我的代碼,所以謝謝。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM