dongshu7162 2017-04-17 16:50
浏览 308
已采纳

MySQL表中的同名字段相互覆盖 - Laravel

So, I need to do a join between 2 tables - items and categories.

I'm coding in Laravel and here is what I have:

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

And then I get some results like these:

{
  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",
},

Both tables have some fields that have the same name, such as id created_at and updated_at. The problem is that, because they have the same name, the values of the one table overwrite the values of the other table. How do I get the 2nd table values to not overwrite the values from the first one when they have the same column name? Or, even better, how do I get both values back (from both tables)? Maybe using the AS keyword somehow?

Thanks for the help.

  • 写回答

1条回答 默认 最新

  • douyou1937 2017-04-17 16:54
    关注

    Yes, you should use the AS keyword for each duplicate fields

    This is how it works :

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

    Note : for the fields that have the same name, use it this way : 'table.field'

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大