CaiWuXiTong/app/Models/Business/BusinessModel.php

69 lines
2.1 KiB
PHP

<?php
namespace App\Models\Business;
use Illuminate\Database\Eloquent\Model;
/**
* Base class for all "business finance" tables that mirror the Excel sheets
* the user supplied (店铺后台税务数据、财务SW规划表、实际SW统计表 etc.).
*
* Each table is scoped to a company (multi-tenant) and the column list drives
* the dynamic Blade views / forms so we don't have to hand-write 11 sets of
* controllers and templates.
*/
abstract class BusinessModel extends Model
{
public $timestamps = true;
protected $guarded = ['id', 'company_id', 'created_at', 'updated_at'];
protected static function booted(): void
{
static::addGlobalScope('company', function ($builder) {
if (company_id()) {
$builder->where($builder->getModel()->getTable() . '.company_id', company_id());
}
});
static::creating(function (self $model) {
if (empty($model->company_id)) {
$model->company_id = company_id();
}
});
}
/**
* Ordered columns (id, then declared columns, then timestamps).
* Used by the Blade views to render the table headers and form fields.
*/
public static function declaredColumns(): array
{
static $cache = [];
$key = static::class;
if (isset($cache[$key])) {
return $cache[$key];
}
/** @var \Illuminate\Database\Schema\SQLiteBuilder $schema */
$schema = (new static())->getConnection()->getSchemaBuilder();
$columns = $schema->getColumnListing((new static())->getTable());
// Re-order: primary key first, then declared columns, then timestamps.
$ordered = array_values(array_filter($columns, function (string $col) {
return ! in_array($col, ['id', 'company_id', 'created_at', 'updated_at'], true);
}));
return $cache[$key] = ['id' => 'id'] + array_combine($ordered, $ordered);
}
/**
* Column human-readable labels (overridable per model).
*/
public static function columnLabels(): array
{
return [];
}
}