【问题标题】:Laravel resource controller and model the same for multiple databasesLaravel 资源控制器和多个数据库的模型相同
【发布时间】:2020-07-17 07:06:51
【问题描述】:

有什么方法可以为多个数据库使用相同的控制器和模型?

例如,我有一个Product 模型和一个ProductController(带有index,show,store,update,destroy 的CRUD 资源控制器)。数据库、模型和控制器是相同的。

我发现更改连接的唯一方法是在模型protected $connection = 'connection_name'; 但是我需要为每个模型复制 ProductController。

我想将ProductController 设为BaseProductController 并为每个数据库扩展它,但我不知道如何设置连接。

【问题讨论】:

  • 即使这可能是一种不好的做法,坏主意,也不是首选方式
  • 为什么要为两个完全相同的数据库维护两个模型和控制器?

标签: database laravel eloquent connection crud


【解决方案1】:

您可以使用 resolving 钩子在您的产品模型上使用依赖注入

在服务提供商中:

use App\Product;

$this->app->resolving(Product::class, function ($product, $app) {
    $request = $app['request'];
    if ($request->isConnection1()) {
        $product->setConnection('connection1');
    }
    elseif ($request->isConnection2()) {
        $product->setConnection('connection2');
    }
});

我的例子显然行不通,因为我不知道你的上下文,但它向你展示了思维方式。

另一种方法是在ProductController 周围的路由中添加一个中间件,该中间件设置数据库默认连接(未指定时由模型使用)

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Database\ConnectionResolverInterface as DatabaseManager;

class SwitchConnection
{
    protected $dbManager;

    public function __construct(DatabaseManager $dbManager)
    {
        $this->dbManager = $dbManager;
    }

    public function handle($request, Closure $next, string $connection)
    {
        $this->dbManager->setDefaultConnection($connection);
        return $next($request);
    }
}

顺便说一句,如果你把这个中间件别名为switch.connection,并把switch.connection:connection1添加到一个路由的中间件中,它会自动切换,因此你可以使用同一个控制器。

【讨论】:

  • 中间件仅适用于 index() 方法。在我将模型作为参数加载的方法上,例如:public function destroy(Product $product) { $delete = $product-&gt;delete(); return $this-&gt;sendResponse([], 'product deleted successfully.'); } 不起作用
猜你喜欢
  • 2018-02-18
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 2014-08-07
相关资源
最近更新 更多