where($builder->getModel()->getTable() . '.store_id', $storeId); } }); // 创建时自动填入 store_id static::creating(function ($model) { if (empty($model->store_id)) { // 创建时:超管若指定 X-Store-Id 则写入该门店;否则落到自身 store_id if ($storeId = self::getCreateStoreId()) { $model->store_id = $storeId; } } }); } public function store(): BelongsTo { return $this->belongsTo(Store::class); } private static function getQueryStoreId(): ?int { $user = auth()->user(); if (!$user) { return null; } // 超管默认总览:不传 X-Store-Id 则不做门店过滤 if ($user->is_super) { if (request()->header('X-Store-Id')) { return (int) request()->header('X-Store-Id'); } return null; } return $user?->store_id; } private static function getCreateStoreId(): ?int { $user = auth()->user(); if (!$user) { return null; } if ($user->is_super && request()->header('X-Store-Id')) { return (int) request()->header('X-Store-Id'); } return $user?->store_id; } }