How can I query raw via Eloquent?

前端 未结 8 1248
眼角桃花
眼角桃花 2020-12-02 20:42

I am trying to do a query in my Laravel app and I want to use a normal structure for my query. This class either does use Eloquent so I need to find something to do a query

8条回答
  •  Happy的楠姐
    2020-12-02 21:05

    You can use hydrate() function to convert your array to the Eloquent models, which Laravel itself internally uses to convert the query results to the models. It's not mentioned in the docs as far as I know.

    Below code is equviolent to $userModels = User::where('id', '>', $userId)->get();:

    $userData = DB::select('SELECT * FROM users WHERE id > ?', [$userId]);
    $userModels = User::hydrate($userData);
    

    hydrate() function is defined in \Illuminate\Database\Eloquent\Builder as:

    /**
     * Create a collection of models from plain arrays.
     *
     * @param  array  $items
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function hydrate(array $items) {}
    

提交回复
热议问题