如何在 Laravel 查询生成器上获取主键名称

Gon*_*afa 6 database query-builder laravel laravel-query-builder

有没有办法使用 Laravel 查询生成器获取表的主键名称?我可以做类似的事情吗

$key = DB::table($someTable)->getPrimaryKey();
Run Code Online (Sandbox Code Playgroud)

我查看了文档和 API,但找不到任何参考资料。

提前致谢。

Tim*_*myG 6

您可以使用架构管理器直接获取表的索引数组:

$indexes = DB::connection()->getDoctrineSchemaManager()->listTableIndexes($table);
Run Code Online (Sandbox Code Playgroud)

或者

$indexes = Schema::getConnection()->getDoctrineSchemaManager()->listTableIndexes($table);
Run Code Online (Sandbox Code Playgroud)

然后您可以获得与该索引键关联的列的数组:

$columns = $indexes[ 'primary' ]->getColumns();
Run Code Online (Sandbox Code Playgroud)

此函数可用于查找您一无所知的表的主键或唯一键:

public function getTablePrimaryOrUniqueKey($table, $key='') {
    //get the array of table indexes
    $indexes = DB::connection()->getDoctrineSchemaManager()->listTableIndexes($table);

    //abort if there are no indexes
    if(!is_array($indexes)) return false;

    //set up the default array of index keys
    $keys = ['primary', 'unique'];

    //if a key was passed and it is valid, use it...but cast as an array
    if($key!='' && in_array($key, $keys)) $keys = (array) $key;

    //loop through the keys array
    foreach ( $keys as $key ) {
        //keep it honest
        if ( array_key_exists( $key, $indexes ) ) {
            //get the columns for this key
            $columns = $indexes[ $key ]->getColumns();

            //if we have an array of columns, we have what we need
            if ( is_array( $columns ) ) {
                return $columns;
            }
        }
    }

    //if you got here, you did not get find what you were looking for
    return false;
}
Run Code Online (Sandbox Code Playgroud)


Phi*_*ter 2

该类Illuminate/Database/Eloquent/Model有一个getKeyName函数是public。

在模型类中,您可以使用 访问主键$this->getKeyName()。