2017-10-04 108 views
2

我试图从PHP和Laravel得到一个MySQL数据库中的唯一行是唯一的。Laravel或PHP与多个条件

在我的数据库,我有:

Email Errors Status 
[email protected] error1 pending 
[email protected] error2 pending 
[email protected] error1 pending 
[email protected] error1 pending 

在我脑海中的解决办法是:

$transactions->unique('email', 'errors', 'status') 

但是,这回这样的:

Email Errors Status 
[email protected] error1 pending 
[email protected] error1 pending 

如果我尝试:

$transactions->unique(['email', 'errors', 'status']) 

它甚至更糟:

Email Errors Status 
[email protected] error1 pending 

我的完美的解决方案会是这样,所以我可以从每个用户看到不同的错误:

Email Errors Status 
[email protected] error1 pending 
[email protected] error2 pending 
[email protected] error1 pending 

基于几个栏这意味着唯一的。

我到处寻找都没有成功,我希望有人能帮助:)

+0

'$ transactions'是一个集合吗? –

+1

看起来好像在数据库中使用组而不是在PHP中使用它会更好。 –

回答

3

你可以...

1)无论是提供自己的功能unique断言:

$transactions->unique(function ($item) { 
    return $item['email'].'/'.$item['errors'].'/'.$item['status']; 
}); 

。 ..假设/符号从来没有在任何领域使用。

2)或作出查询级别这样的分组,使用groupBy方法:

$DB::table('transactions')->select('email', 'errors', 'status') 
->groupBy('email') 
->groupBy('errors') 
->groupBy('status') 
->get(); 

我宁愿去与后者。

+0

非常感谢,最后一个工作完美。那么,我有更多的选择比columnBy列,所以我搞清楚如何做到这一点。我想用一些简短的concat或类似的东西。 – TrOnNe