Laravel中基于Eloquent的模型是否有可能对基础表进行内省/反思并检索有关列的信息(类型,大小,无符号,默认值等)?
或者这是故意遗漏的?
我觉得能够确定列类型(做智能分配一些验证,或帮助推断表单输入类型和/或填充默认值)会很有用。
答案 0 :(得分:1)
我认为你不能在Laravel中“开箱即用”这样做,尽管实施起来相对容易。沿着这些方向,也许是什么?
<?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 => '',
),
...