我想知道如何在Laravel中創建一個名爲「type」的默認變量並將值設置爲「car」。在Laravel中爲選擇查詢添加一個新列,其值爲Laravel
這是到目前爲止我的代碼:
$items = DB::table('items')->orderBy('created_at', 'desc')
->join('items_categories', 'items.item_category_id', '=', 'items_categories.category_id')
->select(
'items.id as items___item_id',
'items.item_title as items___item_title',
'items_categories.id as items_categories___category_id',
'items_categories.title as items_categories___category_title',
)
->take(20);
這工作不錯。但是,我需要爲此選擇的每個記錄獲取/添加自定義鍵和值,以便稍後在模板中使用它來進一步過濾。
因此,我需要添加一個名爲type
的鍵值爲car
,所以在print_r中我會看到type => car用於每條記錄,我可以在我的代碼中使用它。
如何做到這一點?
我可以把這somhow在選擇?
像:
->select(
'items.id as items___item_id',
'items.item_title as items___item_title',
'items_categories.id as items_categories___category_id',
'items_categories.title as items_categories___category_title',
//something like this?
'type' = 'car'
)
因爲現在我得到這樣的:
Array
(
[0] => stdClass Object
(
[items___item_id] => 10
[items___item_user_id] => 2
[items___item_title] => A new blue truck
[items_categories___category_id] => 1
[items_categories___category_title] => Truck
)
[1] => stdClass Object
(
[items___item_id] => 11
[items___item_user_id] => 2
[items___item_title] => VW Tiguan
[items_categories___category_id] => 1
[items_categories___category_title] => SUV
)
,我想這一點:
Array
(
[0] => stdClass Object
(
[items___item_id] => 10
[items___item_user_id] => 2
[items___item_title] => A new blue truck
[items_categories___category_id] => 1
[items_categories___category_title] => Truck
[type] => car
)
[1] => stdClass Object
(
[items___item_id] => 11
[items___item_user_id] => 2
[items___item_title] => VW Tiguan
[items_categories___category_id] => 1
[items_categories___category_title] => SUV
[type] => car
)
如果可能的話,不能在模型文件,但是在一次查詢期間,因爲只有一次我需要做此修改。
任何人都知道該怎麼做? –
你有沒有理由不使用雄辯? –
您是否想根據類型進行選擇? 'car'? –