【问题标题】:How to join two tables without empty column being filled from the other record?如何在没有从另一条记录中填充空列的情况下连接两个表?
【发布时间】:2020-04-19 23:23:02
【问题描述】:

如何连接两个表以使一个记录在特定列上具有空值,而另一记录具有其值?

输出应该是这样的

发生的情况是第二条记录的 B.column3 被同一列的第一条记录的值填充。

我尝试了这段代码,但我无法让它正确。

$orders = self::leftJoin('customer_information', function ($join) {
                $join->on('customer_information.id', '=', 'orders.customer_id')
                ->orWhere('orders.customer_id', '=', null);
            })->get();

我怎样才能做到这一点?

订单表有 - 客户ID - order_id - 总金额

customer_information 有 - ID - 姓名 - 地址

我想从有或没有 customer_id 的连接表中获取所有记录。

PS:

  1. 自我 ==> 订单
  2. orders 表中的 customer_id 有时为空值,因此我无法与 customer_information 表建立关系

我在 Order 模型中做这个。

【问题讨论】:

  • 如果订单没有customer_id,只显示订单并加入customer_information的所有空字段?
  • @TsaiKoga 是否可以只用一个查询?
  • $orders = self::leftJoin('customer_information', 'customer_information.id', '=', 'orders.customer_id')->get()?
  • 这行得通!我的天啊。我想我现在需要睡觉了。我让事情变得如此复杂。非常感谢。干杯!你可能想把它放在答案部分,这样我就可以把它标记为正确的。
  • 不客气,我将其添加到答案中。

标签: laravel


【解决方案1】:

leftjoin 将获得所有带有 customer_informations 或不带 customer_informationorders

$orders = self::leftJoin('customer_information', 'customer_information.id', '=', 'orders.customer_id')->get()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多