如何从 Eloquent 模型静态获取表名?

not*_*eek 8 php static-methods laravel eloquent lumen

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

$s = new Something();
dd($s->getTable());
Run Code Online (Sandbox Code Playgroud)

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

我在想像这样的代码:

Something::getTable();
Run Code Online (Sandbox Code Playgroud)

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

San*_*yen 20

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

public static function getTableName()
{
    return (new self())->getTable();
}
Run Code Online (Sandbox Code Playgroud)

然后你可以得到表名 Something::getTableName()

  • @Ryan 或者基本模型中的“return (new static)->getTable()”。 (2认同)

top*_*her 9

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

  1. 定义特征: app/Traits/CanGetTableNameStatically.php
<?php namespace App\Traits;

trait CanGetTableNameStatically
{
    public static function tableName()
    {
        return with(new static)->getTable();
    }
}
Run Code Online (Sandbox Code Playgroud)
  1. 放入您的Model,或者更好的是,使用 aBaseModel并且您的所有其他模型都扩展了它。

app/Models/BaseModel.php

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Traits\CanGetTableNameStatically;

class BaseModel extends Model
{
    use CanGetTableNameStatically;

    // ...
}
Run Code Online (Sandbox Code Playgroud)
  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';

    // ...
}
Run Code Online (Sandbox Code Playgroud)

用法YourModel::tableName()随处拨打即可。

在视图中:

{{ \App\Models\Customer::tableName() }}
Run Code Online (Sandbox Code Playgroud)

进行连接时:

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


小智 5

不是静态而是优雅的方法

with(new Something)->getTable();
Run Code Online (Sandbox Code Playgroud)