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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题