Cast Laravel query results to class

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

    As of laravel 5.4

    Eloquent models dont have the hydrate() method.

    This has been moved to the Eloquent Builder class.

    https://laravel.com/api/5.4/search.html?search=hydrate

    The Eloquent Builder class requires a few things to get this working manually

    1. A query builder to initialize
    2. A model to hydrate with.

    Here is my working example in some laravel 5.8 code:

                $instance = new $class;
                $table = $instance->getTable();
    
                /** @var \Illuminate\Database\Eloquent\Builder $eloquent_builder*/
                $eloquent_builder = new \Illuminate\Database\Eloquent\Builder(
                    // the Query Builder!
                    DB::connection($connection_name)
                    ->table($table)
                    ->select($columns)
                    ->orderBy($order_by, $order)
                );
    
    
                // Tell Eloquent what you're using to hydrate the query
                $eloquent_builder->setModel($instance);
    
    
                return $eloquent_builder->get();
    

提交回复
热议问题