[英]Query from two tables and orderBy date in laravel
I have two tables each for its Eloquent . 我的Eloquent有两个表。 I would like to get results from each of them for specific field (using where clause) 我想从每个特定领域的结果(使用where子句)
then I want to combine the both resulted array and order them by createdAt date filed 然后我想合并两个结果数组并按createdAt日期将它们排序
How can I achieve this in laravel5 ? 如何在laravel5中实现此目标? I tried make use of relations but can't make it work 我尝试利用关系,但无法使其正常工作
this example of the two arrays separately 两个数组的这个例子分别
$football = Football::where('playerId','=',$id)->get()->toArray();
$tennis= Tennis::where('playerId','=',$id)->get()->toArray();
thanks in advance 提前致谢
Assuming they are on different tables, I can think of 2 solutions: 假设它们在不同的表上,我可以想到两种解决方案:
1)first you have to fetch both results, then you can sort in php using 1)首先您必须获取两个结果,然后可以使用
$results = array_merge($football, $tennis);
usort($results, function($a,$b) {
return $a['created_at'] < $b['created_at'];
});
2) Using raw queries, run a UNION : 2)使用原始查询,运行UNION:
SELECT * FROM (
SELECT * FROM football WHERE playerId = X
UNION ALL
SELECT * FROM tennis WHERE playerId = X
) AS A ORDER BY created_at;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.