将更多属性加载到现有的eloquent模型实例中

时间:2016-11-10 23:00:24

标签: laravel eloquent

是否可以在没有多个查询或hackery的情况下将其他属性加载到模型实例中?让我解释一下:

// I got a tiny model with only id loaded
$model = Model::first(['id']);
// Then some code runs
// Then I decide I'd need `name` and `status` attributes
$model->loadMoreAttributes(['name', 'status']);
// And now I can joyously use name and status without additional queries
$model->name;
$model->status;

Eloquent是否与我虚构的loadMoreAttributes函数类似?

请注意,我不是新手,并且非常了解Model::find($model->id)等。他们太罗嗦了。

感谢你提前注意。

1 个答案:

答案 0 :(得分:1)

您可以将Eloquent模型扩展为具有此loadMoreAttributes方法,如下所示:

use Illuminate\Database\Eloquent\Model;

class YourModel extends Model
{
    public function loadMoreAttributes(array $columns)
    {
        // LIMITATION: can only load other attributes if id field is set.
        if (is_null($this->id)) {
            return $this;
        }

        $newAttributes = self::where('id', $this->id)->first($columns);

        if (! is_null($newAttributes)) {
            $this->forceFill($newAttributes->toArray());
        }

        return $this;
    }
}

这样您就可以在模型上执行此操作:

$model = YourModel::first(['id']);
$model->loadMoreAttributes(['name', 'status']);

<强>限制

然而,这种黑客存在局限性。如果已经提取了模型实例的唯一loadMoreAttributes(),则只能调用id方法。

希望这有帮助!