端口StdClass数据到模型 [英] Port StdClass data to Model

查看:148
本文介绍了端口StdClass数据到模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是如下:

1)数据库中的几个表中有数百万行,所以使用Eloquent并不有效,因为我也有多重关系在这种情况下,解决方案是编写自定义DB :: raw()选择和连接以有效地完成任务。这可以返回一个StdClass,你可能会知道。

1) I have millions of rows in a few tables in the database, so using Eloquent is not efficient, as I have also multiple relationships. The solution in this case was to write custom DB::raw() selects and joins to accomplish the tasks efficiently. This returns a StdClass as you may know.

2)我有4-5个模型有相当冗长的方法,我需要使用,所以最好的解决方案要为StdClass的每一行创建这些模型的实例,然后使用这些方法。

2) I have 4-5 models that have quite lengthy methods, which I need to use, so a best possible solution would be to create instances of those models for each row of the StdClass, and then use those methods.

是否有一个已知的最佳做法,用于移植信息StdClass进入模型,在OOP模式方面?你会怎么解决这个问题?我会采取任何建议,我准备好重新编码。

Is there a known 'best practice' for 'porting' the info from the StdClass into the models, in terms of OOP patterns? How would you guys tackle this problem? I would take any suggestions, I am ready to even restructure the code.

P.S。 Laravel v4.2

P.S. Laravel v4.2

推荐答案

这样的事情会适合你。只需调整它的需求:

Something like this will work for you. Just adjust it to your needs:

public function newFromStd(stdClass $std)
{
    // backup fillable
    $fillable = $this->getFillable();

    // set id and other fields you want to be filled
    $this->fillable(['id', ... ]);

    // fill $this->attributes array
    $this->fill((array) $std);

    // fill $this->original array
    $this->syncOriginal();

    $this->exists = true;

    // restore fillable
    $this->fillable($fillable);

    return $this;
}

那么你可以这样做:

$user = with(new User)->newFromStd( DB::table('users')->first() );

// or make it static if you like:
$user = User::newFromStd( DB::table('users')->first() );

这篇关于端口StdClass数据到模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆