【问题标题】:Dynamic table name for Laravel modelLaravel 模型的动态表名
【发布时间】:2016-09-25 21:05:20
【问题描述】:

对于我的应用程序,我将拥有多个具有相同基本结构的表(自动生成的表)。例如,我有表survey_1survey_2survey_23。是否可以创建这样的模型:new Survey(2),它将为表 survey_2 生成模型?

【问题讨论】:

  • 你做错了。将所有数据放在一张表中,并添加列将数据分成逻辑块。
  • 不,我需要多个表格,因为我正在制作调查表,其中每一列都针对特定的问题类型,每一行都针对填写调查表的人的答案。我的任务是以这种方式构建它,这样我就无法更改数据库结构。
  • @BartBergmans 有一些处理方法不需要每次调查都使用新表格。
  • 就像我说的,我必须像这样构建它。我对此无能为力。
  • 作为一名软件专业人员,您的部分工作是在需求没有意义时向非技术管理人员提出案例。有时我们会遇到不可能/危险的要求,或者只是愚蠢的要求。 “我对此无能为力”很少是真的。

标签: php laravel laravel-5 eloquent


【解决方案1】:

我认为这是可能的。尝试覆盖模型中的 __constructor 方法

class Survey extends Model
{
    public function __construct( array $attributes = [] )
    {
        parent::construct($attributes);
        if (array_key_exists('table', $attributes)) {
           $this->setTable($attributes['table']) ;
        }
        else {
            // do staff when table is not specified 
        }
    }
}

然后

$survey_1 = new Survey(['table' => 'survey_1']); 
$survey_2 = new Survey(['table' => 'survey_2']); 
$survey_3 = new Survey(['table' => 'survey_3']); 

我不知道它是否有效。
但我强烈建议您不要对单独的表格使用您的方法。

【讨论】:

  • 这样做有一个很大的缺点(我今天在和一位同事交谈时遇到了这个问题)。像firstOrCreate 这样的一些 Eloquent 方法会创建一个 new 实例,它会完全忽略您的 $table 名称。目前没有办法解决这个问题。
【解决方案2】:

我有这个。在 laravel 6 中。 我还没有确定这个想法,我想我宁愿拥有多个数据库并使用单独的连接......但这不是问题。

<?php

namespace App\Models\Eloquent;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    
    protected $table = null;
   
    protected $fillable = [
        'data',
    ];

    protected $casts = [
        'data' => 'object',
    ];

    public function setTable($tableName)
    {
        $this->table = $tableName;
    }

    public function scopeTable($query, $tableName)
    {
        $query->getQuery()->from = $tableName;
        return $query;
    }

}

测试路径:

Route::get('/write', function () {

    $project = new \App\Models\Eloquent\Project();
    $project->setTable('project_2');
    $project->data = ['hello' => 'dolly'];
    $project->save();

});

Route::get('/read', function () {

    $data = \App\Models\Eloquent\Project::query()
        ->table('project_2')
        ->where('data', 'like', '%dolly%')
        ->get();

    return $data;

});

但这行得通。 哦是啊。我把我的模型放在 App\Models\Eloquent ... 这是可选的。

【讨论】:

    猜你喜欢
    • 2014-08-24
    • 1970-01-01
    • 2013-10-25
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 2017-11-08
    • 2017-05-22
    • 2019-03-04
    相关资源
    最近更新 更多