如何从 Eloquent 模型中静态获取 table 名称?

How can I get table name, statically from Eloquent model?

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

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

有没有办法在不实例化新的 Something 对象的情况下获得 table?

我在想这些代码:

Something::getTable();

但是会出现..should not be called statically错误

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

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

然后你可以用Something::getTableName()

得到table名字

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

不是静态的而是优雅的方法

with(new Something)->getTable();
  class YourModel extends Model
{
    //

    public static $_table = "table_name";

}

然后像这样访问它

YourModel::$_table

此处稍作修改,以便您可以静态获取模型的 table 名称。

  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 的保留属性上设置自定义 table 名称: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