LoginSignup
1
2

More than 5 years have passed since last update.

LaravelでSHOW COLUMNS FROM hogehoge

Posted at

やりたいこと

Mysqlで実行できるSHOW COLUMNS FROM hogehogeをLaravelでも実行したい。

ちなみにMysqlで実行するとこんなの。
サイトの権限管理用のrolesというテーブル。

mysql> SHOW COLUMNS FROM roles;
+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name       | varchar(191)     | NO   |     | NULL    |                |
| created_at | timestamp        | YES  |     | NULL    |                |
| updated_at | timestamp        | YES  |     | NULL    |                |
| deleted_at | timestamp        | YES  |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

やりかた

SHOW COLUMNS専用のメソッドが無いようなので、こうやるしかなさげ

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class Role extends Model
{
    protected $table = 'roles';

    use SoftDeletes;
    protected $dates = ['deleted_at'];

    public static function showColumns()
    {
        $role       = new Role;
        $sql        = 'SHOW COLUMNS FROM ' . $role->table;
        $columns    = DB::select($sql);
        var_dump($columns);
    }
}

結果

array(5) {
  [0]=>
  object(stdClass)#910 (6) {
    ["Field"]=>
    string(2) "id"
    ["Type"]=>
    string(16) "int(10) unsigned"
    ["Null"]=>
    string(2) "NO"
    ["Key"]=>
    string(3) "PRI"
    ["Default"]=>
    NULL
    ["Extra"]=>
    string(14) "auto_increment"
  }
  [1]=>
  object(stdClass)#911 (6) {
    ["Field"]=>
    string(4) "name"
    ["Type"]=>
    string(12) "varchar(191)"
    ["Null"]=>
    string(2) "NO"
    ["Key"]=>
    string(0) ""
    ["Default"]=>
    NULL
    ["Extra"]=>
    string(0) ""
  }
  [2]=>
  object(stdClass)#909 (6) {
    ["Field"]=>
    string(10) "created_at"
    ["Type"]=>
    string(9) "timestamp"
    ["Null"]=>
    string(3) "YES"
    ["Key"]=>
    string(0) ""
    ["Default"]=>
    NULL
    ["Extra"]=>
    string(0) ""
  }
  [3]=>
  object(stdClass)#913 (6) {
    ["Field"]=>
    string(10) "updated_at"
    ["Type"]=>
    string(9) "timestamp"
    ["Null"]=>
    string(3) "YES"
    ["Key"]=>
    string(0) ""
    ["Default"]=>
    NULL
    ["Extra"]=>
    string(0) ""
  }
  [4]=>
  object(stdClass)#915 (6) {
    ["Field"]=>
    string(10) "deleted_at"
    ["Type"]=>
    string(9) "timestamp"
    ["Null"]=>
    string(3) "YES"
    ["Key"]=>
    string(0) ""
    ["Default"]=>
    NULL
    ["Extra"]=>
    string(0) ""
  }
}
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2