加入两个 Laravel 集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47919492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Join two laravel collection
提问by Rilzzz
I have two Laravel collections. first collection $customer(It has 30 elements):
我有两个 Laravel 集合。第一个集合 $customer(它有 30 个元素):
Collection {#2615 ▼
#items: array:31 [▼
0 => {#2610 ▼
+"allocated_date": "2016-12-01"
+"Customer": "44"
}
1 => {#2616 ▼
+"allocated_date": "2016-12-02"
+"Customer": "42"
}
And other one is $agent(It has 17 elements)
另一个是 $agent(它有 17 个元素)
Collection {#2586 ▼
#items: array:16 [▼
0 => {#2585 ▼
+"agent_allocated_date": "2016-12-01"
+"Agent": "41"
}
1 => {#2587 ▼
+"agent_allocated_date": "2016-12-02"
+"Agent": "95"
}
I need the result like this (leftJoin allocated_date with agent_allocated_date). can not using merge or combine. because number of elements in both collections are different. help me to find the output
我需要这样的结果(leftJoinlocated_date 和 agent_allocated_date)。不能使用合并或组合。因为两个集合中的元素数量不同。帮我找到输出
array:31 [▼
0 => {#2596 ▼
+"allocated_date": "2016-12-01"
+"Customer": "44"
+"agent_allocated_date": "2016-12-01"
+"Agent": "41"
}
回答by madalinivascu
You need to map over the customer and find the agent for that customer and merge the two collections:
您需要映射客户并找到该客户的代理并合并两个集合:
$customer= $customer->map(function ($item, $key) {
$single_agent = $agent->where('agent_allocated_date',$item->agent_allocated_date);
return collect($item)->merge($single_agent);
});
回答by Etibar
$result = [];
foreach($collection as $datas){
foreach($datas as $data){
$result[] = $data;
}
}
回答by Rahul Chauhan
The better approach to execute join query. I have tested this join query. It's working. Try this one.
执行连接查询的更好方法。我已经测试了这个连接查询。它正在工作。试试这个。
$data = DB::table('customer')->select('customer.allocated_date','customer.Customer','agent.agent_allocated_date','agent.Agent')->join('agent','agent.id','=','customer.id');
print_r($data);