亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel:針對不同條件的查詢構建器基礎查詢

Laravel:針對不同條件的查詢構建器基礎查詢

PHP
婷婷同學_ 2023-05-26 17:45:12
在我的應用程序中,有一種情況我必須運行相同的查詢 3 次,但每個查詢都有一些不同的條件。例如:active:查詢 + active conditions,inactive:查詢 + inactive conditions。ETC。這是我的代碼:$activeInventory = $inactiveInventory = \DB::table('device_inventories')  ->where([    'device_companies.company_id'  => session()->get('COMPANY_ID'),    'device_inventories.device_id' => $Self->id,  ])->select([    ...  ])  ->join('devices', 'devices.id', '=', 'device_inventories.device_id')  ->join('device_companies', 'device_companies.id', '=', 'devices.device_company_id');// active records$active = $activeInventory  ->where('device_inventories.status', 'T')  ->join('u_devices', 'u_devices.device_inventory_id', '!=', 'device_inventories.id')  ->get() ?? null;// inactive records$inactive = $inactiveInventory  ->where('device_inventories.status', 'F')  ->get() ?? null;// returning datareturn [  'model' => $Self,  'active' => $active,  'inactive' => $inactive,];u_devices請注意,我已在查詢中加入表Active。但是當我運行Inactive查詢時,join withu_devices也出現在該查詢中。即使我使用不同的變量來存儲基本查詢并運行它。我在這里做錯了什么..?
查看完整描述

2 回答

?
MM們

TA貢獻1886條經驗 獲得超2個贊

這是由于附加查詢邏輯的工作方式所致。當您將更改附加到查詢的一個版本時,它會修改原始版本,因此來自基礎的任何后續查詢也會受到影響。您應該能夠使它與clonePHP 中的關鍵字一起使用:


$baseQuery = \DB::table('device_inventories')->where([

  'device_companies.company_id'  => session()->get('COMPANY_ID'),

  'device_inventories.device_id' => $Self->id,

])->select([

  ...

])

->join('devices', 'devices.id', '=', 'device_inventories.device_id')

->join('device_companies', 'device_companies.id', '=', 'devices.device_company_id');


$active = (clone $baseQuery)->where('device_inventories.status', 'T')

->join('u_devices', 'u_devices.device_inventory_id', '!=', 'device_inventories.id')

->get() ?? null;


$inactive = (clone $baseQuery)->where('device_inventories.status', 'F')->get() ?? null;


return [

  'model' => $Self,

  'active' => $active,

  'inactive' => $inactive,

];

當您使用 時clone,您創建了查詢的副本,因為它是您代碼中的那個點,因此后續使用不會“污染”查詢。


查看完整回答
反對 回復 2023-05-26
?
守候你守候我

TA貢獻1802條經驗 獲得超10個贊

您需要獲取構建器對象的新實例。$activeInventory持有你告訴它的所有條件,其中包括所有條件where。您將需要構建器的副本對其執行不同的查詢:

$something = (clone $activeInventory)->...;
$else = (clone $activeInventory)->...;


查看完整回答
反對 回復 2023-05-26
  • 2 回答
  • 0 關注
  • 220 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號