所以我有兩個表,組織和聯繫人。這兩個表都有列「電子郵件」,我需要做的是保持組織的名稱,但在電子郵件列中連接所有電子郵件(組織的+所有聯繫電子郵件)。Laravel連接表和連接行
這裏有一些版本我沒有運氣
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)這個實際上是非常接近,但它不篩選出項目既沒有接觸或客戶entires有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 line 333: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? group by
customers
.id
' at line 12/2 QueryException in Connection.php line 713: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? group by
customers
.id
' at line 1 (SQL: selectcustomers
.id
,customers
.name
,registration
, GROUP_CONCAT(DISTINCT contacts.email, ", ") AS contact_emails,customers
.customers
left joincontacts
oncontacts
.customer_id
=customers
.id
and LENGTH(contacts.email) 4 group bycustomers
.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'));
})
我首先想到的是子查詢:http://dev.mysql.com/doc/refman/5.7/en/subqueries.html - 但問題實際上就是爲什麼要分析所有電子郵件。他們以後會不會在單獨的形式中有任何價值? – Kjell
我正在通過yajra datatables在單個表中提供結果。 –
@Kjell我實際上試過子查詢。用失敗的例子更新了我的問題。 –