【问题标题】:SQL Select data from two tables, one row -> multiple rowsSQL 从两个表中选择数据,一行 -> 多行
【发布时间】:2020-05-30 08:12:06
【问题描述】:

我有以下两张表:

customers:  |  phones:
--------------------------------------
id          |  id
name        |  owner (FK_CUSTOMERS)
address     |  number

我在 laravel Blade 中加载了一个 html 表格来显示所有客户,我想要一个表格单元格,其中包含为每个客户保存的电话。

因此,一位客户可能没有手机,只有一部或多部手机。我需要用他们的手机连续检索每个客户,或者有更好的方法吗?

如果我这样做会导致每部手机出现一行重复数据:

 $customers = DB::table('customers')
        ->join("phones","customers.id", "=", "phones.owner")
        ->where("phones.group",1)
        ->select(
            'customers.id',            
            'customers.name',            
            'customers.fiscalNumber',            
            'customers.disscount',   
            'customers.billAddress',   
            'customers.tax',
            'phones.number'                   
        )
        ->get();

我想要这个:

id | name    | address          | phones
5  | Michael | fake address 123 | 666777888,111222333,444555666

我尝试了几件事,但没有任何效果。谢谢

【问题讨论】:

    标签: php mysql laravel laravel-query-builder


    【解决方案1】:

    您应该按 id 对客户进行分组,并使用 group_concat 将所有电话号码提取为逗号分隔的字符串。它应该看起来像这样:

    $customers = DB::table('customers')
        ->join("phones","customers.id", "=", "phones.owner")
        ->where("phones.group",1)
        ->select(
            'customers.id',
            'customers.name',
            'customers.fiscalNumber',
            'customers.disscount',
            'customers.billAddress',
            'customers.tax',
            DB::raw('group_concat(phones.number) as number')
        )
        ->groupBy('customers.id')
        ->get();
    

    【讨论】:

    • 我刚刚注意到的一个问题是没有电话的客户不会出现。有什么办法解决这个问题吗?谢谢
    • 使用leftJoin 而不是join
    【解决方案2】:

    而不是加入您的表格,这有时是使用 Eloquent 的反模式。使用 Eloquent mutators 来解决你的问题。

    定义与音素和突变体的关系。

    class Customer {
        public function phones() {
            return $this->hasMany(Phone::class, 'owner');
        }
    
        public function getPhoneNumbersAttribute() {
            return implode(',', $this->phones->pluck('number')->all());
        }
    }
    

    要使用你的 mutator,只需获取你的模型并访问它。为了优化性能,请使用 with() 方法加载手机,该方法会立即加载关系。

    Customer::with('phones')->find(1)->phoneNumbers; // [666777888,111222333,444555666]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多