How to create a Eloquent model instance from a raw Object?

徘徊边缘 提交于 2019-12-22 04:44:13

问题


I need to make a raw database query using Laravel:

$results = DB::select("SELECT * FROM members 
    INNER JOIN (several other tables) 
    WHERE (horribly complicated thing) 
    LIMIT 1");

I get back a plain PHP StdClass Object with fields for the properties on the members table. I'd like to convert that to a Member (an Eloquent model instance), which looks like this:

use Illuminate\Database\Eloquent\Model;

class Member extends Model {
}

I'm not sure how to do it since a Member doesn't have any fields set on it, and I'm worried I will not initialize it properly. What is the best way to achieve that?


回答1:


You can try to hydrate your results to Model objects:

$results = DB::select("SELECT * FROM members 
                       INNER JOIN (several other tables) 
                       WHERE (horribly complicated thing) 
                       LIMIT 1");

$models = Member::hydrate( $results->toArray() );

Or you can even let Laravel auto-hydrate them for you from the raw query:

$models = Member::hydrateRaw( "SELECT * FROM members...");

EDIT

From Laravel 5.4 hydrateRaw is no more available. We can use fromQuery instead:

$models = Member::fromQuery( "SELECT * FROM members..."); 



回答2:


You can simply init a new model:

$member = new App\Member;

Then you can assign the columns:

$member->column = '';

Or if all columns are mass assignable:

$member->fill((array)$results);

Or have I misunderstood something?




回答3:


You should definetly use Eloquent to perform that.

You might declare the relations between the models, and use the where conditions.

like:

Member::where(......)->get();

This will return an eloquent instance, and you can do whatever you need.



来源:https://stackoverflow.com/questions/40855116/how-to-create-a-eloquent-model-instance-from-a-raw-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!