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()
这里稍作修改,以便您可以静态获取模型的表名。
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)
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)
protected $tableapp/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)
| 归档时间: |
|
| 查看次数: |
9075 次 |
| 最近记录: |