如何从laravel中的表中选择所有列名?

问题描述 投票:2回答:6

我试图从表Teller中获取所有列名

功能:

public function getTableColumns($tables)
{
    return DB::select(DB::raw('SELECT 
                                    COLUMN_NAME, 
                                    DATA_TYPE, 
                                    COLUMN_DEFAULT
                                FROM 
                                    INFORMATION_SCHEMA.COLUMNS
                                WHERE 
                                    table_name = `Teller`'));
}
php laravel laravel-5
6个回答
24
投票

您可以通过简单地完成所有列名称...

public function getTableColumns($table)
{
    return DB::getSchemaBuilder()->getColumnListing($table);

    // OR

    return Schema::getColumnListing($table);

}

8
投票

从模型中获取表名称

$product = new Product;
$table = $product->getTable();
print_r($table);

从模型中获取表列名称

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{   
    public function getTableColumns() {
        return $this->getConnection()->getSchemaBuilder()->getColumnListing($this->getTable());
    }
}

现在您将获得“products”表的所有列,如果您需要它在控制器中,那么您可以通过以下方式获取它:

 $product=new Product;
 $columns=$product->getTableColumns();
 print_r($columns);

0
投票

如果您有多个数据库连接,请查看以下内容:

添加到php脚本的顶部

use Illuminate\Support\Facades\Schema;

检索代码中的任何位置

使用数据库连接

$columns = Schema::Connection('business')->getColumnListing('users'); // 'business' is your database connection

        echo "<pre>";
        print_r($columns);
        exit();

没有数据库连接

$columns = Schema::getColumnListing('users');

    echo "<pre>";
    print_r($columns);
    exit();

-1
投票

要从表中获取所有行:

 $users = DB::table('users')->get();

此方法将直接返回列的值:

$email = DB::table('users')->where('name', 'John')->value('email');

参考:

https://laravel.com/docs/5.1/queries


-1
投票

你可以简单地写:

public function getTableColumns($tables)
{
    return DB::select(
        DB::raw('SELECT * FROM `Teller`')
    );
}

如果你有Teller模型,你也可以使用Teller::all();

更新

要获取所有列名称,您可以运行SHOW FIELDS Teller


-1
投票

你可以用它

DB::table('table_name')->get();
© www.soinside.com 2019 - 2024. All rights reserved.