How to get database field type in Laravel?

后端 未结 9 2128
离开以前
离开以前 2020-12-14 01:38

Is there a way to get the datatype of a database table field? Almost like a inverse of migration.

For example, if the migration of a users table column looks like

9条回答
  •  醉酒成梦
    2020-12-14 02:14

    Short answer: Yes, that functionality exists

    After scouring the code, I found that you could. Skip below to "The Solution" to see it.

    Eloquent, and the Database classes, use PDO, which does not tie you a specific SQL-based database.

    Therefore, you should be able to do something like this:

    $pdo = DB::getPdo();
    

    Note that the connection object can return the instance of PDO.

    There are some methods like getColumnMeta, but they aren't fully supported across all drivers.

    However, some googling seems to point out that the best way might be to use ANSI-standard INFORMATION_SCHEMA - using sql queries to get that information.

    The solution

    Lastly, Laravel includes the Doctrine library as a dependency, which does contain some schema functionality.

    Sidenote: Doctrine is, in fact, included for its schema-based functionalities - Laravel doesn't use Doctrine's ORM

    See here on the same connection object where we retrieved the PDO instance, we can get the doctrine connection and schema manager. You should be able to call:

    $schema = DB:: getDoctrineSchemaManager();
    

    You can then use the schema manager (docs here) to get what you're after.

提交回复
热议问题