Cast Laravel query results to class

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

    Typically you'd achieve this by setting the PDO Statement fetch_style to PDO::FETCH_CLASS as below

    $statement->fetchAll(PDO::FETCH_CLASS, "App\User");

    If you look at the method Illuminate\Database\Connection::select you'll see that whilst you can set the fetch_style/fetchMode, you can not the second argument.

    public function select($query, $bindings = array(), $useReadPdo = true)
    {
        return $this->run($query, $bindings, function($me, $query, $bindings) use ($useReadPdo)
        {
            if ($me->pretending()) return array();
    
            // For select statements, we'll simply execute the query and return an array
            // of the database result set. Each element in the array will be a single
            // row from the database table, and will either be an array or objects.
            $statement = $this->getPdoForSelect($useReadPdo)->prepare($query);
    
            $statement->execute($me->prepareBindings($bindings));
    
            return $statement->fetchAll($me->getFetchMode());
        });
    }
    

    Nor can you get access to the statement before fetchAll is called to call PDOStatement::setFetchMode for example.

    You could perhaps attempt to extend Illuminate\Database\Connection and utilise that throughout other Database related classes by extending and replacing where necessary but it seems like a hefty task to maintain.

    The other option is to use Eloquent which will give you classes back of a particular type but you get the slight additional overhead of hydrating the model objects.

    class Foo extends Illuminate\Database\Eloquent\Model {
        protected $table = 'foo';
    }
    
    Foo::all()
    Foo::where('col', 1)->get()
    

提交回复
热议问题