在 Slim 中使用 Eloquent
最后更新于:2022-04-01 22:34:13
# 在 Slim 中使用 Eloquent
你可以使用 [Eloquent](https://laravel.com/docs/5.1/eloquent) 这种数据库 ORM 将你的 Slim 应用程序连接到数据库。
## 为你的应用程序添加 Eloquent
```
composer require illuminate/database "~5.1"
```
Figure 1: Add Eloquent to your application.
## 配置 Eloquent
在 Slim 的 setting 数组中添加数据库设置项。
```
[
// Slim Settings
'determineRouteBeforeAppMiddleware' => false,
'displayErrorDetails' => true,
'db' => [
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'user',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
]
],
];
```
Figure 2: Settings array.
在 `dependencies.php` 中,或者其他任意位置添加你的 Service Factories:
```
// Service factory for the ORM
$container['db'] = function ($container) {
$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection($container['settings']['db']);
$capsule->setAsGlobal();
$capsule->bootEloquent();
return $capsule;
};
```
Figure 3: Configure Eloquent.
## 传递数据表实例到控制器
```
$container[App\WidgetController::class] = function ($c) {
$view = $c->get('view');
$logger = $c->get('logger')
$table = $c->get('db')->table('table_name');
return new \App\WidgetController($view, $logger, $table);
};
```
Figure 4: Pass table object into a controller.
## 从控制器中查询数据表
```
view = $view;
$this->logger = $logger;
$this->table = $table;
}
public function __invoke(Request $request, Response $response, $args)
{
$widgets = $this->table->get();
$this->view->render($response, 'app/index.twig', [
'widgets' => $widgets
]);
return $response;
}
}
```
Figure 5: Sample controller querying the table.
### 使用 where 查询数据表
```
...
$records = $this->table->where('name', 'like', '%foo%')->get();
...
```
Figure 6: Query searching for names matching foo.
### 通过 id 查询数据表
```
...
$record = $this->table->find(1);
...
```
Figure 7: Selecting a row based on id.
## 了解更多
[Eloquent](https://laravel.com/docs/5.1/eloquent) 文档
';