2017-04-17 187 views
0

所以,我需要在2個表格 - 項目和類別之間進行連接。MySQL表中的同名字段相互覆蓋 - Laravel

我編碼Laravel這裏就是我:

$items = DB::table('items') 
      ->join('categories', 'categories.id', '=', 'items.category_id') 
      ->get(); 

然後我得到了一定的成果這樣的:

{ 
    id: 3, 
    barcode: "0002", 
    category_id: "4", 
    price: 200, 
    in_use: 1, 
    serial_number: 1112, 
    model: "Toshiba", 
    condition_id: 3, 
    person_id: 1, 
    comments: "A monitor that is usually connected to a laptop.", 
    created_at: "2017-03-28 19:50:02", 
    updated_at: "2017-03-28 19:50:02", 
    name: "monitor", 
}, 
{ 
    id: 3, 
    barcode: "0003", 
    category_id: "4", 
    price: 300, 
    in_use: 1, 
    serial_number: 11342, 
    model: "Toshiba", 
    condition_id: 3, 
    person_id: 1, 
    comments: "A monitor that is usually connected to a laptop.", 
    created_at: "2017-03-28 19:50:02", 
    updated_at: "2017-03-28 19:50:02", 
    name: "monitor", 
}, 

兩個表都有一些字段具有相同的名稱如idcreated_atupdated_at。 問題是,因爲它們具有相同的名稱,所以一個表的值會覆蓋另一個表的值。 如何獲得第二個表值不覆蓋第一個值時,他們有相同的列名? 或者,甚至更好,我如何從兩個表中獲得兩個值? 也許使用AS關鍵字?

感謝您的幫助。

回答

1

是的,你應該使用AS關鍵字每個重複字段

這是它如何工作的:

$items = DB::table('items') 
     ->join('categories', 'categories.id', '=', 'items.category_id') 
     ->select('field1', 'field2 as field2name', 'field3') 
     ->get(); 

注:對於具有相同名稱的領域,使用這種方式:「 table.field'

+0

謝謝。這可能是一個解決方案。但是有沒有辦法不指定我需要的每一個領域? – padawanTony

+1

如果您有兩個表的示例,您可以從一個表中選擇所有內容,只需更改另一個表的名稱,例如,從類別中選擇所有內容,然後從項目中重命名。 要從一張表中選擇所有內容,請使用'table。*' –