所以我有两张桌子,组织和联系人。这两个表都有“电子邮件”栏,我需要做的是保留组织的名称,但是在电子邮件栏中连接所有的电子邮件(组织的+所有的联系邮件)。
以下是我尝试过的一些没有运气的版本
( 1)这个不分组:
$customers = DB::table('customers')
->whereRaw('LENGTH(customers.email) > 4')
->select([
'customers.id',
'customers.name',
'customers.email'
]);
$contacts = DB::table('contacts')
->whereRaw('LENGTH(contacts.email) > 4')
->leftJoin('customers', 'contacts.customer_id', '=', 'customers.id')
->select([
'customers.id',
'customers.name',
'contacts.email'
]);
return $customers
->union($contacts)
->select([
'id',
'name',
DB::raw('GROUP_CONCAT(DISTINCT email, ", ") AS emails'),
])
->groupBy('id')
->get();2)这一项实际上相当接近,但它不过滤那些既没有DB::raw('LENGTH(email) > 4'),也没有客户实体的条目
return $customers = DB::table('customers')
->leftJoin('contacts', 'contacts.customer_id', '=', 'customers.id')
->select([
'customers.id',
'customers.name',
'registration',
DB::raw('GROUP_CONCAT(DISTINCT contacts.email, ", ") AS contact_emails'),
'customers.email'
])
->groupBy('customers.id')
->get();3)我试着使用子查询(我知道它只会过滤掉没有电子邮件的联系人)。
3.1)尝试子查询1会导致错误:不存在JoinClause::whereRaw()
return $customers = DB::table('customers')
->leftJoin('contacts', function($join) {
$join->on('contacts.customer_id', '=', 'customers.id')
->whereRaw('LENGTH(email) > 4');
})...3.2)这一项产生以下语法错误:
return $customers = DB::table('customers')
->leftJoin('contacts', function($join) {
$join->on('contacts.customer_id', '=', 'customers.id')
->where(DB::raw('LENGTH(email) > 4'));
})1/2 PDOException in Connection.php第333行: SQLSTATE42000:语法错误或访问冲突: 1064您的SQL语法中有错误;检查与MySQL服务器版本对应的手册,以获得正确的语法使用near '?组由
customers.id‘在第一行 2/2 QueryException in Connection.php第713行: SQLSTATE42000:语法错误或访问冲突: 1064您的SQL语法中有错误;检查与MySQL服务器版本对应的手册,以获得使用near‘的正确语法?customers.id‘在第1行(SQL:选择customers.id、customers.name、registration、GROUP_CONCAT(不同的contacts.email,“、")为contact_emails、customers.customers左联接contacts.contacts.d25= customers.id和长度(contacts.email)4组按customers.id)
3.3)有些例子说我应该这样做,但这会产生错误Not enough arguments for the on clause.
return $customers = DB::table('customers')
->leftJoin('contacts', function($join) {
$join->on('contacts.customer_id', '=', 'customers.id');
$join->on(DB::raw('LENGTH(contacts.email) > 4'));
})发布于 2016-12-02 19:42:11
这对我有用。没有语法错误,并过滤掉长度小于4个字符的联系人:
DB::table('customers')
->leftJoin('contacts', function ($join) {
$join->on('contacts.customer_id', '=', 'customers.id')
->where(DB::raw('length(contacts.email)'), '>', 4);
})
->select([
'customers.id',
'customers.name',
DB::raw('group_concat(distinct contacts.email separator ", ") AS contact_emails'),
])
->groupBy('customers.id')
->get();在Laravel5.3.26,MySQL 5.6.20 (无严格模式)中进行测试。
https://stackoverflow.com/questions/40930192
复制相似问题