【问题标题】:How can I get table name, statically from Eloquent model?如何从 Eloquent 模型中静态获取表名?
【发布时间】:2019-01-29 12:31:20
【问题描述】:

现在我有这段代码可以检查 Eloquent 模型连接到哪个表。

$s = new Something();
dd($s->getTable());

无论如何我可以在不实例化新的Something 对象的情况下获取表格吗?

我在想这些代码:

Something::getTable();

但是会有..should not be called statically的错误。

【问题讨论】:

  • (new static)->getTable()
  • @Inazo 这与 PHP 中静态的(法语?)文档无关。
  • 问题是可用于为模型指定自定义表名的$table 变量不是静态的,因此您无法静态访问它。这很奇怪,但也是设计使然。 (在表名下阅读eloquent model conventions
  • 我为this question 写了一个答案,也回答了你的问题。此外,您可以通过这种方式调用静态函数来获取表名。无需制作对象。

标签: php laravel eloquent static-methods lumen


【解决方案1】:

您可以添加到您的模型中。

public static function getTableName()
{
    return (new self())->getTable();
}

然后你可以用Something::getTableName()获取表名

【讨论】:

  • 如果您想在实际模型扩展的父模型中定义 getTableName()get_called_class() 会很有帮助。 stackoverflow.com/a/283094/470749
  • @Ryan 或 return (new static)->getTable() 在基本模型中。
【解决方案2】:

$model = 新模型; 回声 $model->getTable(); 试试这个

【讨论】:

  • 这正是他想要避免的,实例化新模型实例
【解决方案3】:

不是静态而是优雅的方法

with(new Something)->getTable();

【讨论】:

    【解决方案4】:
      class YourModel extends Model
    {
        //
    
        public static $_table = "table_name";
    
    }
    

    然后像这样访问它

    YourModel::$_table
    

    【讨论】:

      【解决方案5】:

      这里稍作修改,以便您可以静态获取模型的表名。

      1. 定义特征:app/Traits/CanGetTableNameStatically.php
      <?php namespace App\Traits;
      
      trait CanGetTableNameStatically
      {
          public static function tableName()
          {
              return with(new static)->getTable();
          }
      }
      
      1. 输入您的Model,或者更好的是,使用BaseModel,您的所有其他模型都扩展了它。

      app/Models/BaseModel.php

      <?php namespace App\Models;
      
      use Illuminate\Database\Eloquent\Model;
      use App\Traits\CanGetTableNameStatically;
      
      class BaseModel extends Model
      {
          use CanGetTableNameStatically;
      
          // ...
      }
      
      1. 在你的其他模型上,你可以在 Laravel 的保留属性上设置自定义表名:protected $table

      app/Models/Customer.php

      <?php namespace App\Models\Master;
      
      use App\Models\BaseModel;
      
      class Customer extends BaseModel
      {
          protected $table = 'my_customers';
      
          // ...
      }
      

      用法:在任何地方拨打YourModel::tableName()即可。

      在视图中:

      {{ \App\Models\Customer::tableName() }}
      

      在进行连接时:

      DB::table( Product::tableName() . ' AS p' )
      ->leftJoin( ProductCategory::tableName() . ' AS pc', 'pc.id', '=', 'p.category_id')
      // ... etc
      

      【讨论】:

      • +1 这是我在寻找答案并根据需要使用时自己想出的确切解决方案。
      • 当它只被基本模型使用时,为什么要让它成为一个特征?
      猜你喜欢
      • 2020-01-06
      • 1970-01-01
      • 2014-12-19
      • 2016-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多