> ## Documentation Index
> Fetch the complete documentation index at: https://docs.base44.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Entities モジュール

> データモデルの CRUD 操作。`base44.entities.EntityName.method()` 経由でアクセスします。

<Warning>
  このページは AI コーディングエージェントスキルの一部で、人間ではなくエージェント向けに書かれています。人間向けの Base44 ドキュメントは [デベロッパードキュメント](/developers) を参照してください。
</Warning>

# Entities モジュール

データモデルの CRUD 操作。`base44.entities.EntityName.method()` 経由でアクセスします。

## 目次

* [メソッド](#methods)
* [例](#examples) (Create、Bulk Create、List、Filter、Get、Update、Delete、Subscribe)
* [User エンティティ](#user-entity)
* [サービスロールアクセス](#service-role-access)
* [権限](#permissions)

## メソッド

**注意:** `list()` と `filter()` の最大制限はリクエストごとに 5,000 アイテムです。

| メソッド                                           | シグネチャ                       | 説明                                   |
| ---------------------------------------------- | --------------------------- | ------------------------------------ |
| `create(data)`                                 | `Promise<T>`                | 1 つのレコードを作成                          |
| `bulkCreate(dataArray)`                        | `Promise<T[]>`              | 複数のレコードを作成                           |
| `list(sort?, limit?, skip?, fields?)`          | `Promise<Pick<T, K>[]>`     | すべてのレコードを取得 (ページ分割)                  |
| `filter(query, sort?, limit?, skip?, fields?)` | `Promise<Pick<T, K>[]>`     | 条件に一致するレコードを取得                       |
| `get(id)`                                      | `Promise<T>`                | ID で単一レコードを取得                        |
| `update(id, data)`                             | `Promise<T>`                | レコードを更新 (部分更新)                       |
| `updateMany(query, data)`                      | `Promise<UpdateManyResult>` | MongoDB 更新演算子を使って一致するすべてのレコードを更新     |
| `bulkUpdate(dataArray)`                        | `Promise<T[]>`              | ID で複数のレコードを更新、それぞれに独自のデータ           |
| `delete(id)`                                   | `Promise<DeleteResult>`     | ID でレコードを削除                          |
| `deleteMany(query)`                            | `Promise<DeleteManyResult>` | 一致するすべてのレコードを削除                      |
| `importEntities(file)`                         | `Promise<ImportResult<T>>`  | CSV からインポート (フロントエンドのみ)              |
| `subscribe(callback)`                          | `() => void`                | リアルタイム更新をサブスクライブ (unsubscribe 関数を返す) |

## 例

### 作成

```javascript theme={null}
const task = await base44.entities.Task.create({
  title: "Complete documentation",
  status: "pending",
  dueDate: "2024-12-31"
});
```

### 一括作成

```javascript theme={null}
const tasks = await base44.entities.Task.bulkCreate([
  { title: "Task 1", status: "pending" },
  { title: "Task 2", status: "pending" }
]);
```

### ページ分割付きリスト

```javascript theme={null}
// Get first 10 records, sorted by created_date descending (max 5,000 per request)
const tasks = await base44.entities.Task.list(
  "-created_date",  // sort (SortField: prefix with - for descending)
  10,               // limit
  0                 // skip
);

// Get next page
const page2 = await base44.entities.Task.list("-created_date", 10, 10);
```

### フィルター

```javascript theme={null}
// Simple filter
const pending = await base44.entities.Task.filter({ status: "pending" });

// Multiple conditions
const myPending = await base44.entities.Task.filter({
  status: "pending",
  assignedTo: userId
});

// With sort, limit, skip (max 5,000 per request)
const recent = await base44.entities.Task.filter(
  { status: "pending" },
  "-created_date",  // sort (SortField: prefix with - for descending)
  5,
  0
);

// Select specific fields
const titles = await base44.entities.Task.filter(
  { status: "pending" },
  null,
  null,
  null,
  ["id", "title"]
);
```

### ID で取得

```javascript theme={null}
const task = await base44.entities.Task.get("task-id-123");
```

### 更新

```javascript theme={null}
// Partial update - only specified fields change
await base44.entities.Task.update("task-id-123", {
  status: "completed",
  completedAt: new Date().toISOString()
});
```

### 削除

```javascript theme={null}
// Single record
const result = await base44.entities.Task.delete("task-id-123");
console.log("Deleted:", result.success);

// Multiple records matching query
const manyResult = await base44.entities.Task.deleteMany({ status: "archived" });
console.log("Deleted:", manyResult.deleted);
```

### Update Many (MongoDB スタイル)

```javascript theme={null}
// Update all pending tasks to status "in-progress"
const result = await base44.entities.Task.updateMany(
  { status: "pending" },                     // query: which records to update
  { $set: { status: "in-progress" } }        // MongoDB update operator
);
console.log("Updated:", result.updated);

// Increment a counter field
await base44.entities.Task.updateMany(
  { category: "bugs" },
  { $inc: { priority: 1 } }
);
```

### 一括更新 (ID で)

```javascript theme={null}
// Update multiple records, each with different data
const updated = await base44.entities.Task.bulkUpdate([
  { id: "task-1", status: "done", completedAt: new Date().toISOString() },
  { id: "task-2", status: "in-progress", assignedTo: userId },
  { id: "task-3", priority: 5 }
]);
```

### ファイルからインポート

```javascript theme={null}
// Frontend only: import from CSV/file
const result = await base44.entities.Task.importEntities(file);
if (result.status === "success" && result.output) {
  console.log(`Imported ${result.output.length} records`);
} else {
  console.error(result.details);
}
```

### リアルタイム更新のサブスクライブ

```javascript theme={null}
// Subscribe to all changes on Task entity
const unsubscribe = base44.entities.Task.subscribe((event) => {
  console.log(`Task ${event.id} was ${event.type}:`, event.data);
  // event.type is "create", "update", or "delete"
});

// Later: unsubscribe to stop receiving updates
unsubscribe();
```

**イベント構造:**

```javascript theme={null}
{
  type: "create" | "update" | "delete",
  data: { ... },       // the entity data
  id: "entity-id",     // the affected entity's ID
  timestamp: "2024-01-15T10:30:00Z"
}
```

## User エンティティ

すべてのアプリには特別なルールを持つ組み込みの `User` エンティティがあります:

* 通常のユーザーは **自分自身の** レコードのみを読み取り/更新可能
* `entities.create()` 経由でユーザーを作成することはできません - 代わりに `auth.register()` を使用
* サービスロールはすべてのユーザーレコードにフルアクセス可能

```javascript theme={null}
// Get current user's record
const me = await base44.entities.User.get(currentUserId);

// Service role: get any user
const anyUser = await base44.asServiceRole.entities.User.get(userId);
```

## サービスロールアクセス

管理者レベルの操作 (ユーザー権限をバイパス):

```javascript theme={null}
// Backend only
const allTasks = await base44.asServiceRole.entities.Task.list();
const allUsers = await base44.asServiceRole.entities.User.list();
```

## 権限 (RLS と FLS)

データアクセスは、エンティティスキーマで定義された **行レベルセキュリティ (RLS)** と **フィールドレベルセキュリティ (FLS)** ルールによって制御されます。

1. **認証レベル**: 匿名、認証済み、またはサービスロール
2. **RLS ルール**: ユーザーがどのレコード (行) を作成/読み取り/更新/削除できるかを制御
3. **FLS ルール**: アクセス可能なレコード内でユーザーがどのフィールドを読み取り/書き込みできるかを制御

操作はこれらのルールに基づいて成功または失敗します - 部分的な結果はありません。

RLS と FLS はエンティティスキーマファイル (`base44/entities/*.jsonc`) で構成されます。構成の詳細については、[entities-create.md](https://docs.base44.com/developers/skills/base44-sdk/references/../../base44-cli/references/entities-create.md#row-level-security-rls) を参照してください。

**注意:** `asServiceRole` はユーザーのロールを `"admin"` に設定しますが、RLS をバイパスしません。サービスロール操作が成功するには、RLS ルールに管理者アクセス (例: `{ "user_condition": { "role": "admin" } }`) を含める必要があります。

## 型定義

### RealtimeEvent

```typescript theme={null}
/** Event types for realtime entity updates. */
type RealtimeEventType = "create" | "update" | "delete";

/** Payload received when a realtime event occurs. */
interface RealtimeEvent<T = any> {
  /** The type of change that occurred. */
  type: RealtimeEventType;
  /** The entity data. */
  data: T;
  /** The unique identifier of the affected entity. */
  id: string;
  /** ISO 8601 timestamp of when the event occurred. */
  timestamp: string;
}

/** Callback function invoked when a realtime event occurs. */
type RealtimeCallback<T = any> = (event: RealtimeEvent<T>) => void;
```

### 結果の型

```typescript theme={null}
/** Result returned when updating multiple entities. */
interface UpdateManyResult {
  /** Whether the update was successful. */
  success: boolean;
  /** Number of entities that were updated. */
  updated: number;
}

/** Result returned when deleting a single entity. */
interface DeleteResult {
  /** Whether the deletion was successful. */
  success: boolean;
}

/** Result returned when deleting multiple entities. */
interface DeleteManyResult {
  /** Whether the deletion was successful. */
  success: boolean;
  /** Number of entities that were deleted. */
  deleted: number;
}

/** Result returned when importing entities from a file. */
interface ImportResult<T = any> {
  /** Status of the import operation. */
  status: "success" | "error";
  /** Details message, e.g., "Successfully imported 3 entities with RLS enforcement". */
  details: string | null;
  /** Array of created entity objects when successful, or null on error. */
  output: T[] | null;
}
```

### SortField とサーバーフィールド

```typescript theme={null}
/**
 * Sort field type for entity queries.
 * Supports ascending (no prefix or '+') and descending ('-') sorting.
 * Example: 'created_date', '+created_date', '-created_date'
 */
type SortField<T> = (keyof T & string) | `+${keyof T & string}` | `-${keyof T & string}`;

/** Fields added by the server to every entity record. */
interface ServerEntityFields {
  id: string;
  created_date: string;
  updated_date: string;
  created_by?: string | null;
  created_by_id?: string | null;
  is_sample?: boolean;
}
```

### 型レジストリ (型付きエンティティ用)

**型付きエンティティの取得方法:** Base44 CLI はプロジェクトからエンティティインターフェースと `EntityTypeRegistry` の拡張を生成できます。実行方法については、**base44-cli** スキルを使用してください。

```typescript theme={null}
/**
 * Registry mapping entity names to their TypeScript types.
 * Augment this interface with your entity schema (user-defined fields only).
 * Typically populated by the Base44 CLI type generator.
 */
interface EntityTypeRegistry {}

/**
 * Full record type for each entity: schema fields + server-injected fields.
 */
type EntityRecord = {
  [K in keyof EntityTypeRegistry]: EntityTypeRegistry[K] & ServerEntityFields;
};
```

### EntityHandler

```typescript theme={null}
/** Entity handler providing CRUD operations for a specific entity type. */
interface EntityHandler<T = any> {
  /** Lists records with optional pagination and sorting. Max 5,000 per request. */
  list<K extends keyof T = keyof T>(
    sort?: SortField<T>,
    limit?: number,
    skip?: number,
    fields?: K[]
  ): Promise<Pick<T, K>[]>;

  /** Filters records based on a query. Max 5,000 per request. */
  filter<K extends keyof T = keyof T>(
    query: Partial<T>,
    sort?: SortField<T>,
    limit?: number,
    skip?: number,
    fields?: K[]
  ): Promise<Pick<T, K>[]>;

  /** Gets a single record by ID. */
  get(id: string): Promise<T>;

  /** Creates a new record. */
  create(data: Partial<T>): Promise<T>;

  /** Updates an existing record. */
  update(id: string, data: Partial<T>): Promise<T>;

  /** Deletes a single record by ID. */
  delete(id: string): Promise<DeleteResult>;

  /** Deletes multiple records matching a query. */
  deleteMany(query: Partial<T>): Promise<DeleteManyResult>;

  /** Creates multiple records in a single request. */
  bulkCreate(data: Partial<T>[]): Promise<T[]>;

  /**
   * Updates multiple records matching a query using MongoDB update operators.
   * @param query - Filter to select which records to update.
   * @param data - MongoDB update operator object (e.g., `{ $set: { field: value } }`).
   */
  updateMany(query: Partial<T>, data: Record<string, Record<string, any>>): Promise<UpdateManyResult>;

  /** Updates multiple records by ID, each with its own update data. */
  bulkUpdate(data: (Partial<T> & { id: string })[]): Promise<T[]>;

  /** Imports records from a file (frontend only). */
  importEntities(file: File): Promise<ImportResult<T>>;

  /** Subscribes to realtime updates. Returns unsubscribe function. */
  subscribe(callback: RealtimeCallback<T>): () => void;
}
```

### EntitiesModule

```typescript theme={null}
/** Entities module: typed registry keys get typed handlers; dynamic access remains untyped. */
type EntitiesModule = TypedEntitiesModule & DynamicEntitiesModule;

type TypedEntitiesModule = {
  [K in keyof EntityTypeRegistry]: EntityHandler<EntityRecord[K]>;
};

type DynamicEntitiesModule = {
  [entityName: string]: EntityHandler<any>;
};
```

<Note>このページは AI を使用して翻訳されました。最も正確で最新の情報については、[英語版](/) を参照してください。 </Note>
