问题
Is it possible for an Eloquent-based model in Laravel to introspect/reflect on the underlying table and retrieve information (type, size, unsigned, default values, etc) about the columns?
Or is this intentionally left out?
I feel like it would be useful to be able to determine the column type (to do things like intelligently assign some validations, or help infer a form input type and/or populate a default).
回答1:
I don't think you can do this "out of the box" in Laravel, though it would be relatively easy to implement. Something along these lines, maybe?
<?php
class Model extends Eloquent {
public function describe()
{
$table = $this->getTable();
$pdo = \DB::connection()->getPdo();
return $pdo->query("describe $table")->fetchAll();
}
}
$model = new Model;
$columns = $model->describe();
// $columns:
array (
0 =>
array (
'Field' => 'id',
0 => 'id',
'Type' => 'int(10) unsigned',
1 => 'int(10) unsigned',
'Null' => 'NO',
2 => 'NO',
'Key' => 'PRI',
3 => 'PRI',
'Default' => NULL,
4 => NULL,
'Extra' => 'auto_increment',
5 => 'auto_increment',
),
1 =>
array (
'Field' => 'created_at',
0 => 'created_at',
'Type' => 'timestamp',
1 => 'timestamp',
'Null' => 'NO',
2 => 'NO',
'Key' => '',
3 => '',
'Default' => '0000-00-00 00:00:00',
4 => '0000-00-00 00:00:00',
'Extra' => '',
5 => '',
),
...
来源:https://stackoverflow.com/questions/24700739/can-eloquent-models-retrieve-metadata-on-their-rows