Cast Laravel query results to class

前端 未结 6 1387
清酒与你
清酒与你 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:39

    Laravel 5.8

    In the class you want to cast to (YourClass in this example) to you'll need constructor like this:

        /**
         * Use to initialize fields from DB query like:
         * $query->mapInto(YourClass::class)
         *
         * YourClass constructor.
         * @param \stdClass $data
         */
        public function __construct(\stdClass $data)
        {
            foreach ($data as $key => $value) {
                $this->$key = $value;
            }
        }
    

    Then in your query:

    $result = $query
    ->get()
    ->mapInto(YourClass::class);
    

    $result will now contain a collection of YourClass instances with fields loaded from the query.

提交回复
热议问题