Laravel按表名

时间:2016-05-29 18:30:53

标签: php laravel

有没有办法按表名获取模型?

例如,我有一个“用户”模型,其表定义为protected $table = "users"

现在,我想做的是按表名称获取模型,该名称等于“用户”。

此功能更像是Model::getTable();

的反向

我到处搜索但我找不到解决方案,也许我可能会遗漏一些简单的东西?

修改

我正在构建类似API的东西:

Route::get('/{table}', 'ApiController@api');
Route::get('/{table}/filter', 'ApiController@filter');
Route::get('/{table}/sort', 'ApiController@sort');
Route::get('/{table}/search', 'ApiController@search');

所以在地址栏中,例如当我搜索“用户”时,我可以点击网址:

api/users/search?id=1

然后在控制器上,例如:

public function search(){
  // get all the params

  // get the model function
  $model = //function to get model by table name

  // do some filtering, then return the model
  return $model;
}

7 个答案:

答案 0 :(得分:6)

也许这样的事情可以帮到你:

frame=   70 fps=0.0 q=-0.0 Lsize=     701kB time=00:00:02.33 bitrate=2465.4kbits/s speed= 2.9x 

答案 1 :(得分:2)

您必须确定要调用哪个类的表名。 我看到了两种方法。

使用Laravel的模型命名约定为@IgorRynkovoy建议

使用某种字典

public function search($tableName)
{
    $dictionary = [
        'table_name' => 'CLASS_NAME_WITH_NAMESPACE',
        'another_table_name' => 'CLASS_NAME_WITH_NAMESPACE',
    ];

    $className = $dictionary[$tableName];
    $models = null;

    if(class_exists($className)) {
        $models = $className::all();
    }

    // do some filtering, then return the model
    return $models;
}

答案 2 :(得分:1)

我知道这是一个老问题,但它可以帮助某人:

public function getModelFromTable($table)
{
    foreach( get_declared_classes() as $class ) {
        if( is_subclass_of( $class, 'Illuminate\Database\Eloquent\Model' ) ) {
            $model = new $class;
            if ($model->getTable() === $table)
                return $class;
        }
    }

    return false;
}

它将返回类名,因此您需要实例化它。

答案 3 :(得分:0)

替代变体。 我有基本模型App \ Models \ Model 该模型具有静态方法getModelByTable,当然您可以将其存储在所需的任何位置。

$ smashing start
Thin web server (v1.7.2 codename Bachmanity)
Maximum connections set to 1024
Listening on 0.0.0.0:3030, CTRL+C to stop
{ 47249764683760 rufus-scheduler intercepted an error:
  47249764683760   job:
  47249764683760     Rufus::Scheduler::EveryJob "10s" {:first_in=>0}
  47249764683760   error:
  47249764683760     47249764683760
  47249764683760     JSON::ParserError
  47249764683760     784: unexpected token at '<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 404 Not Found</title>
</head>
<body><h2>HTTP ERROR 404</h2>
<p>Problem accessing /job/DEMO/lastBuild/api/json. Reason:
<pre>    Not Found</pre></p><hr><a href="http://eclipse.org/jetty">Powered by Jetty:// 9.4.z-SNAPSHOT</a><hr/>

</body>
</html>
'
  47249764683760       /home/smashing/.rbenv/versions/2.3.7/lib/ruby/2.3.0/json/common.rb:156:in `parse'
  47249764683760       /home/smashing/.rbenv/versions/2.3.7/lib/ruby/2.3.0/json/common.rb:156:in `parse'
  47249764683760       /home/smashing/my-project/jobs/jenkins_build.rb:41:in `get_json_for_job'
  47249764683760       /home/smashing/my-project/jobs/jenkins_build.rb:48:in `block (2 levels) in <top (required)>'
  47249764683760       /home/smashing/.rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/rufus-scheduler-3.4.2/lib/rufus/scheduler/jobs.rb:210:in `do_call'
  47249764683760       /home/smashing/.rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/rufus-scheduler-3.4.2/lib/rufus/scheduler/jobs.rb:254:in `trigger_now'
  47249764683760       /home/smashing/.rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/rufus-scheduler-3.4.2/lib/rufus/scheduler/jobs.rb:296:in `block (3 levels) in start_work_thread'
  47249764683760       /home/smashing/.rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/rufus-scheduler-3.4.2/lib/rufus/scheduler/jobs.rb:299:in `block (2 levels) in start_work_thread'
  47249764683760       /home/smashing/.rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/rufus-scheduler-3.4.2/lib/rufus/scheduler/jobs.rb:285:in `loop'
  47249764683760       /home/smashing/.rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/rufus-scheduler-3.4.2/lib/rufus/scheduler/jobs.rb:285:in `block in start_work_thread'
  47249764683760   tz:
  47249764683760     ENV['TZ']:
  47249764683760     Time.now: 2019-07-05 17:03:56 +0530
  47249764683760     local_tzone: #<TZInfo::DataTimezone: Asia/Kolkata>
  47249764683760   et-orbi:
  47249764683760     (etz:nil,tnz:"IST",tziv:"2.0.0",tzidv:nil,rv:"2.3.7",rp:"x86_64-linux",win:false,rorv:nil,astz:nil,eov:"1.2.1",eotnz:#<TZInfo::DataTimezone: Asia/Kolkata>,eotnfz:"+0530",eotlzn:"Asia/Kolkata",eotnfZ:"IST",debian:nil,centos:nil,osx:"Asia/Kolkata")
  47249764683760   scheduler:
  47249764683760     object_id: 47249768596520
  47249764683760     opts:
  47249764683760       {}
  47249764683760       frequency: 0.3
  47249764683760       scheduler_lock: #<Rufus::Scheduler::NullLock:0x000055f263588260>
  47249764683760       trigger_lock: #<Rufus::Scheduler::NullLock:0x000055f263588030>
  47249764683760     uptime: 0.30658841133117676 (306)
  47249764683760     down?: false
  47249764683760     threads: 2
  47249764683760       thread: #<Thread:0x000055f263585f88>
  47249764683760       thread_key: rufus_scheduler_47249768596520
  47249764683760       work_threads: 1
  47249764683760         active: 1
  47249764683760         vacant: 0
  47249764683760         max_work_threads: 28
  47249764683760       mutexes: {}
  47249764683760     jobs: 4
  47249764683760       at_jobs: 0
  47249764683760       in_jobs: 0
  47249764683760       every_jobs: 4
  47249764683760       interval_jobs: 0
  47249764683760       cron_jobs: 0
  47249764683760     running_jobs: 1
  47249764683760     work_queue: 0
} 47249764683760 .

答案 4 :(得分:0)

studly_case()str_singular()是不推荐使用的功能。

您可以使用Illuminate\Support\Str门面。

$className = 'App\\' . Str::studly(Str::singular($tableName));

答案 5 :(得分:0)

从以下继承,而不是从 Model 继承。

 $ruta = 'pila/' . $anio . '/' . $mes;

        $nombreArchivo = date('Y-m-d H:i:s') . '_' . $datosEmpresa['TIDE'] . '_' . $datosEmpresa['IDEM'] . '_' . $datosEmpresa['OPERADOR'] . '_' . $datosEmpresa['PERIODO'] . '_' . $datosEmpresa['TIPOPLANILLA'] . '_TIPO_2.txt';

        $archivo = $ruta . '/' . $nombreArchivo;

        $contenido = null;

        /* - - - - - - - - - - - - - - - - - *
         *          REGISTRO TIPO 1          *
         * - - - - - - - - - - - - - - - - - */

        $campo1 = '01';
        $campo2 = str_pad($datosEmpresa['MPLA'], 1);
        $campo3 = str_pad('0001', 4);
        $campo4 = str_pad($datosEmpresa['RASO'], 200);
        $campo5 = str_pad($datosEmpresa['TIDE'], 2);
        $campo6 = str_pad($datosEmpresa['IDEM'], 16);
        $campo7 = str_pad($datosEmpresa['DIGV'], 1);
        $campo8 = str_pad($datosEmpresa['TIPOPLANILLA'], 1);
        $campo9 = str_pad($datosEmpresa['PLANILLAANTERIOR'], 10);
        $campo10 = str_pad($datosEmpresa['FECHAPLANILLAANT'], 10);
        $campo11 = str_pad($datosEmpresa['PRESENTACION'], 1);
        $campo12 = str_pad($datosEmpresa['CODSUCURSAL'], 10);
        $campo13 = str_pad($datosEmpresa['NOMSUCURSAL'], 40);
        $campo14 = str_pad($datosEmpresa['CARL'], 6);
        $campo15 = str_pad($datosEmpresa['PERIODO'], 7);
        $campo16 = str_pad($datosEmpresa['PERIODOSALUD'], 7);
        $campo17 = str_pad(" ", 10); //PLANILLA
        $campo18 = str_pad(" ", 10); //FECHA PAGO
        $campo19 = str_pad(count($datosTrabajador), 5, '0', STR_PAD_LEFT);
        $campo20 = str_pad($datosEmpresa['TOTALNOMINA'], 12, '0', STR_PAD_LEFT);
        $campo21 = str_pad($datosEmpresa['TAPO'], 2);
        $campo22 = str_pad($datosEmpresa['OPERADOR'], 2);

        $contenido .= $campo1 . $campo2 . $campo3 . $campo4 . $campo5 . $campo6 . $campo7 . $campo8 . $campo9 . $campo10 . $campo11 . $campo12 . $campo13 . $campo14 . $campo15 . $campo16 . $campo17 . $campo18 . $campo19 . $campo20 . $campo21 . $campo22;

        Storage::append($archivo, $contenido);

要覆盖自动猜测的表名,请将其添加到您的 EnhancedModel 后代类中:

use Illuminate\Support\Str;

class EnhancedModel extends \Illuminate\Database\Eloquent\Model
{
    /**
     * The table associated with the model. Copies $table in Model
     *
     * @var string
     */
    protected static string $tableName;

    /**
     * Get the table associated with the model. Copies getTable() in Model
     *
     * @return string
     */
    public static function getTableName(): string
    {
        return static::$tableName ?? Str::snake(Str::pluralStudly(class_basename(static::class)));
    }

    /**
     * Get the table associated with the model. Overrides getTable() in Model
     *
     * @return string
     */
    public function getTable(): string
    {
        return $this::getTableName();
    }
}

答案 6 :(得分:0)

看起来 Laravel 6 做了一些改变。以下对我来说很好


    use Illuminate\Support\Str;
    ....
    $className = 'App\\' . Str::studly(str::singular($table_name));
       if(class_exists($className)) {
        $model = new $className; 
       }