gpt4 book ai didi

php - 从数据库返回时,Laravel 将模型转换为另一个模型

转载 作者:行者123 更新时间:2023-12-04 02:30:47 26 4
gpt4 key购买 nike

背景信息

我有一个名为Product 的模型。产品可以有 3 种不同的进货方式:SerializeBulkNone

  • Serialize 当每个物理项目都有条形码时选择。
  • Bulk 当我们关注数量变化时选择
  • 当我们想要在库存中包含产品但我们不关心数量时选择。

我想做什么

我想创建这 3 个模型(序列化、批量、无)并将它们扩展到产品。然后能够调用类似 Product::all() 的东西并获得这样的集合:

Products [
0 => Serialize[...]
1 => Serialize[...]
2 => Bulk[...]
3 => None[...]
...
500 => Bulk[...]
]

我的问题

如何让 Laravel 自动将每个对象转换为各自的类?


数据库架构 Database Schema


我的模型结构

产品型号

class Product extends Model
{
use HasFactory;

/**
* The attributes that aren't mass assignable.
*
* @var array
*/
protected $guarded = ['id'];

/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'purchase_price' => MoneyCast::class,
'rental_price' => MoneyCast::class,
'is_active' => 'boolean',
];

/**
* Get active products only
*
* @param Builder $builder
*
* @return Builder
*/
public function scopeActive(Builder $builder): Builder
{
return $builder->where('is_active', '=', true);
}

/**
* Get inactive products only
*
* @param Builder $builder
*
* @return Builder
*/
public function scopeInactive(Builder $builder): Builder
{
return $builder->where('is_active', '=', false);
}

/**
* Set the name and slug when saving to database
*
* @param $value
*/
public function setNameAttribute($value): void
{
$this->attributes['name'] = $value;
$this->attributes['slug'] = Str::slug($value);
}

/**
* Get the products full name
*
* @return string
*/
public function getFullNameAttribute(): string
{
return $this->details
? "{$this->name} {$this->details}"
: $this->name;
}

/**
* Calculate total stocks
*
* @return int
*/
abstract public function getTotalAttribute(): int;

/**
* Calculate total stocks in quarantine
*
* @return int
*/
abstract public function getQuarantinedAttribute(): int;

/**
* Calculate available stocks
*
* @return int
*/
public function getAvailableAttribute(): int
{
return $this->getTotalAttribute() - $this->getQuarantinedAttribute();
}

/**
* Get brand
*
* @return BelongsTo
*/
public function brand(): BelongsTo
{
return $this->belongsTo(Brand::class);
}

/**
* Get category
*
* @return BelongsTo
*/
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}

序列化模型

class Serialize extends Product
{
/**
* Calculate total stocks
*
* @return int
*/
public function getTotalAttribute(): int
{
return $this->stocks()->count();
}

/**
* Calculate total stocks in quarantine
*
* @return int
*/
public function getQuarantinedAttribute(): int
{
return $this->stocks->sum(function ($stock) {
return $stock->repairs()
->where('status', '!=', last(Repair::STATUSES))
->where('is_working', '=', false)
->count();
});
}

/**
* Get associated stocks
*
* @return HasMany
*/
public function stocks(): HasMany
{
return $this->hasMany(Stock::class)->orderBy('barcode');
}
}

批量模型

class Bulk extends Product
{
/**
* Calculate total stocks
*
* @return int
*/
public function getTotalAttribute(): int
{
return $this->transactions()->sum('quantity');
}

/**
* Calculate total stocks in quarantine
*
* @return int
*/
public function getQuarantinedAttribute(): int
{
return $this->stocks->sum(function ($stock) {
return $stock->repairs()
->where('status', '!=', last(Repair::STATUSES))
->where('is_working', '=', false)
->sum('quantity');
});
}

/**
* Get bulk stock transactions.
*
* @return HasMany
*/
public function transactions(): HasMany
{
return $this->hasMany(Transaction::class)->latest();
}
}

最佳答案

您可以基于 stock 方法返回这些子类型的新实例:

Product::all()
->map(function($product) {
switch( $product->stock_method ) {
case 'Serialize':
return new Serialize((array) $product);
case 'Bulk':
return new Bulk((array) $product);
// and so on..
}
return $product;
});

你也可以覆盖 get 方法,这样就不必在每个 all 上都写这段代码了

class Product extends Model {
// static method 'all' calls 'get' defined in Illuminate\Database\EloquentBuilder
public function get($columns = ['*']) {
return parent::get($columns)
->map(function($product) {
switch( $product->stock_method ) {
case 'Serialize':
return new Serialize((array) $product);
case 'Bulk':
return new Bulk((array) $product);
// and so on..
}
return $product;
});
}

关于php - 从数据库返回时,Laravel 将模型转换为另一个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64307293/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com