Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/243.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 对Laravel 5.2上的模型查询进行排序、筛选,然后重新排序_Php_Mysql_Laravel 5 - Fatal编程技术网

Php 对Laravel 5.2上的模型查询进行排序、筛选,然后重新排序

Php 对Laravel 5.2上的模型查询进行排序、筛选,然后重新排序,php,mysql,laravel-5,Php,Mysql,Laravel 5,我已经搜了好几个小时了,没有成功 我有一个产品表,我需要从畅销书/最高评级/最受欢迎的产品列表(100个,来自示例)中随机选取N个产品 使用原始查询,这似乎微不足道。首先我们购买了100种高价产品,然后我们重新订购,最后购买了其中的3种 select * from (select * from `products` order by `valoration` desc limit 100) as products order by RAND() limit 3; 这可以使用DB:table完成

我已经搜了好几个小时了,没有成功

我有一个产品表,我需要从畅销书/最高评级/最受欢迎的产品列表(100个,来自示例)中随机选取N个产品

使用原始查询,这似乎微不足道。首先我们购买了100种高价产品,然后我们重新订购,最后购买了其中的3种

select * from (select * from `products` order by `valoration` desc limit 100) as products order by RAND() limit 3;
这可以使用DB:table完成,但我需要执行相同的查询,而不是使用原始查询。这是因为我的产品模型有许多自定义方法,DB:table返回stdobject的列表,而不是产品模型的集合

在没有原始查询的情况下,如何做到这一点


谢谢。

通过内存,您可以使用Illumb\Support\Collection方法获取所需内容

$selectedProducts = Product::orderBy('valoration')->take(100)->get()->random(3);

要从原始查询中获取模型对象的集合,可以使用
hydrateRaw()

hydrateRaw(string$query,array$bindings=array(),string | null$connection=null)

从原始查询创建模型集合


()

elokent\Collection
扩展了
Support\Collection
,因此拥有了它的所有方法。因此没有必要使用
collect()
。它确实扩展了
Support\Collection
,但我在过去偶然发现了不同的方法行为,因此,如果第一种方法不起作用,我会给出第二种选择。好的,我明白你的意思。在这种情况下,函数实际上没有被重写()!还用另一个模型进行了测试。第一个解决方案有效,将删除解决方案。。。
$products = Product::hydrateRaw("
    select * from (
        select * from `products` order by `valoration` desc limit 100
    ) as products 
    order by RAND() limit 3
");