是否可以在没有多个查询或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)
等。他们太罗嗦了。
感谢你提前注意。
答案 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
方法。
希望这有帮助!