Cast Laravel query results to class

前端 未结 6 1438
清酒与你
清酒与你 2021-02-02 12:04

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?

6条回答
  •  情深已故
    2021-02-02 12:35

    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);
    

    Edit: Found some documentation on the hydrate method too, if that helps

    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.

提交回复
热议问题