【问题标题】:Integrity constraint violation: How to join two tables违反完整性约束:如何连接两个表
【发布时间】:2018-03-03 17:43:51
【问题描述】:

我正在为 laravel 中的一个学校项目制作程序,所以我尝试加入两个表:产品和目的地

表 Product 有以下列:id、name

Destinations 表包含以下列:Destinations:id,product_id,destination,quantity,target_person

我需要加入product_idid

products = DB::table('products')
    ->leftJoin('destinations','id','=','destinations.product_id ')
    ->get();

但是当我尝试使用LEFT JOIN 时,我收到以下错误:

SQLSTATE[23000]:完整性约束违规:1052 on 子句中的列 'id' 不明确(SQL:select * from products inner join destinations on id = destinations.product_id

【问题讨论】:

    标签: php mysql join


    【解决方案1】:

    是因为它不知道“id”是指产品还是目的地中的那个。 试试这个:

    products = DB::table('products')
    ->leftJoin('destinations','products.id','=','destinations.product_id')
    
    ->get();
    

    【讨论】:

      【解决方案2】:

      使用表引用products.id

      products = DB::table('products')
          ->leftJoin('destinations','products.id','=','destinations.product_id')
          ->get();
      

      【讨论】:

      • 工作,但我收到以下错误:SQLSTATE[42S22]:找不到列:1054 Unknown column 'destinations.product_id' in 'on clause'(SQL:select * from products left join destinations on products.id = destinations.product_id ) 但我的数据库中有这个专栏
      • 我已经更新了我的答案,我删除了product_id末尾的空格
      • 别忘了接受正确答案。接受的答案将在未来对其他用户有所帮助
      猜你喜欢
      • 2023-03-28
      • 2020-01-14
      • 2021-12-13
      • 2017-10-01
      • 2019-04-12
      • 1970-01-01
      • 2015-05-26
      相关资源
      最近更新 更多