雄辩的模特可以在其行上检索元数据? [英] Can Eloquent models retrieve metadata on their rows?
问题描述
Laravel中基于口述的模型是否有可能对底层表进行内省/反映,并检索有关列的信息(类型,大小,无符号,默认值等)?
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).
推荐答案
p>我不认为你可以在Laravel的开箱即用中做到这一点,尽管实施起来相对容易。可能吗?
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 => '',
),
...
这篇关于雄辩的模特可以在其行上检索元数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!