在我的 laravel(7.x) 应用程序中,我有一个通用功能来显示所有模块中所有事件和非事件记录的计数。因此,我有义务在每个模块上重复相同的功能。
例如:Device、DeviceType、DeviceCompany 等
模型有一个相同的方法称为 _getTotal
并且 _getTotal
方法在任何地方都做同样的事情工作。
设备.php
class Device extends Model
{
protected $table = 'devices';
...
public function _getTotal($status = \Common::STATUS_ACTIVE)
{
return self::where([
'status' => $status
])->count() ?? 0;
}
}
DeviceType.php
class DeviceType extends Model
{
protected $table = 'device_types';
...
public function _getTotal($status = \Common::STATUS_ACTIVE)
{
return self::where([
'status' => $status
])->count() ?? 0;
}
}
我试图将此方法放在 Base Model
中,但我认为这可能不是一个好的做法。我说得对吗?
有什么方法可以使此方法 _getTotal
成为所有模块的通用方法..?
最佳答案
您可以将此方法移至特征并将该特征包含在所有需要此方法的类中。
trait DeviceStatusTotal
{
public function _getTotal($status = \Common::STATUS_ACTIVE)
{
return self::where([
'status' => $status
])->count() ?? 0;
}
}
DeviceType.php
class DeviceType extends Model
{
use DeviceStatusTotal;
protected $table = 'device_types';
// ...
}
关于Laravel:为所有模型创建一个通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61018868/