将Laravel的查询结果上传到课堂 [英] Cast Laravel query results to class
问题描述
使用语法 DB :: table('foo')
创建查询时,会创建一个泛型类(stdClass)。有没有办法将生成的行转换到特定的类?
When creating a query using the syntax DB::table('foo')
, it creates a generic class (stdClass). Is there any way to cast the resulting rows to a specific class?
这里是一些示例代码,应该解释我想做什么:
Here is some example code that should explain what I want to do:
$result = DB::table('foo')->get();
$converted = (Foo) $result; // Not going to work
我想将数组的所有(stdClass)对象转换为Foo类。
I want to cast all the (stdClass) objects of the array to the Foo class.
推荐答案
是的,您可以将结果合并到所需的类中。我发现这个答案埋在一堆混乱的半答案和困惑的问题,弥补了可怕的 Laracasts.com论坛。感谢您在这里提问,而不是在那里。
Yes, you can hydrate the results into the classes you want. I found the answer buried deep in a mess of half-answers and confused questions that make up the terrible Laracasts.com forum. Thanks for asking the question here instead of there.
一旦你得到结果,就可以使用你的模型类来达到这个目的:
Once you get the results, hydrate them using your model class:
$result = DB::table('foo')->get();
$converted = Foo::hydrate($result);
编辑:找到一些文件在水合物
方法也如此这有助于
Found some documentation on the hydrate
method too, if that helps
编辑2:我发现自己处于需要从数组
或集合
,具体取决于查询的结果。当一个集合被返回时,它被正确地水化,但是当结果是数组时,它们只是 stdClass
。 我写了一个快速方法添加到我的主人模型
采集数组或对象或分页对象的集合,并将其正确地转换为我想要的对象。
Edit 2: I found myself in a situation where I needed to cast results from either an array
or a collection
, depending on the results of a query. When a collection was returned, it was correctly hydrated, but when the result was an array, they were just stdClass
. I wrote a quick method added to my master model
that took a collection of arrays or objects, or a pagination object, and correctly cast it to the object I wanted.
这篇关于将Laravel的查询结果上传到课堂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!