在eloquent模型中获取主键名称

KoI*_*IeY 8 eloquent laravel-4

如何从laravel模型中获取主键名称?

像这样

dd(User::primaryKeyName()); // -> 'user_id'
Run Code Online (Sandbox Code Playgroud)

如果'order'为空,我想在primary上对数据进行排序

$data = User::orderBy(Input::get('order', User::primaryKey()), 'ASC')->get();
Run Code Online (Sandbox Code Playgroud)

但有

Non-static method Illuminate\Database\Eloquent\Model::getKeyName() should not be called statically, assuming $this from incompatible context
Run Code Online (Sandbox Code Playgroud)

Bog*_*dan 14

该方法尝试从受保护的类属性中获取值,return $this->primaryKey;并$this需要来自类实例的上下文.如果你真的需要动态获取该名称,你可以这样做:

App::make('User')->getKeyName();
Run Code Online (Sandbox Code Playgroud)

所以你的代码看起来像这样:

$data = User::orderBy(Input::get('order', App::make('User')->getKeyName()), 'ASC')->get();
Run Code Online (Sandbox Code Playgroud)


mar*_*iro 8

最快的方法可能是这样:

(new User)->getKeyName();
(new User)->getTable();
Run Code Online (Sandbox Code Playgroud)

但是,我认为下面的两种方法为该方法提供了一个更清晰的界面。

第一种方法在您的基本模型类上使用静态方法:

class BaseModel extends Model
{
    protected static function KeyName() {
        return (new static)->getKeyName();
    }

    protected static function TableName() {
        return (new static)->getTable();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的模型中从这个类继承:

class ModelName extends BaseModel
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用: ModelName::KeyName();

如果您无权访问基本模型类,您还可以使用特征:

trait EloquentGetTableNameTrait
{
    public static function TableName()
    {
        return (new static)->getTable();
    }
}
Run Code Online (Sandbox Code Playgroud)

您在模型中像这样使用:

class ModelName
{
    use EloquentGetTableNameTrait;

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

不幸的是,所有这些方法都需要实例化模型的一个实例,但目前没有其他方法可以检索此值。

参考:https : //github.com/laravel/framework/issues/1436

  • +1 对于有效的方法。您引用的问题还包含一些其他不错的解决方案,例如在创建实例 `(new User)->getTable()` 时链接方法调用,它与 `User::tableName()` 一样可读,并且本质上是相同,因此您可能也希望将其包含在您的答案中。 (2认同)