嗯我有同样的问题,我自己写了一个小脚本,它生成基类并解决了外键问题。这是一个基本的解决方案,仅确定“hasOne”关系,您以后可能必须将其更改为 hasMany。我使用了控制器并在视图中构建了我的代码模板:
控制器:
namespace Admin;
/**
* just a quick helper to generate model classes
* from mysql to Eloquent style ones..
* @author Mario
*/
class ModelController extends \BaseController {
/**
* save Classes in folder of choice
*
* @return void
*/
public function create($folder)
{
$sql = "SELECT * FROM information_schema.tables WHERE table_schema = 'UR_SCHEMA'";
$tables = \DB::select($sql);
$sql2 = "select * from information_schema.`KEY_COLUMN_USAGE` where constraint_schema = 'UR_SCHEMA' order by table_name";
$keys = \DB::select($sql2);
$meta = $this->sortOutMetadata($keys);
foreach ($tables as $table) {
$metaData = null;
if(!empty($meta[$table->TABLE_NAME])){
$metaData = $meta[$table->TABLE_NAME];
}
$code = \View::make('model.start', array('table' => $table, 'meta' => $metaData))->render();
file_put_contents($folder.DIRECTORY_SEPARATOR.ucfirst(camel_case($table->TABLE_NAME).'.php'), $code);
}
}
/**
* provide structure indexed by table
*
* @param type $keys
* @return type
*/
private function sortOutMetadata($keys)
{
$return = array();
foreach ($keys as $key) {
if ($key->CONSTRAINT_NAME == 'PRIMARY') {
$return[$key->TABLE_NAME]['pk'] = $key->COLUMN_NAME;
} elseif (!empty($key->REFERENCED_TABLE_NAME)) {
//one way
$return[$key->TABLE_NAME]['fk'][] = array('column' => $key->COLUMN_NAME,
'refColumn' => $key->REFERENCED_COLUMN_NAME,
'refTable' => $key->REFERENCED_TABLE_NAME,);
//and the other
$return[$key->REFERENCED_TABLE_NAME]['fk'][] = array('column' => $key->REFERENCED_COLUMN_NAME,
'refColumn' => $key->COLUMN_NAME,
'refTable' => $key->TABLE_NAME,);
}
}
return $return;
}
}
我的视图模板(几乎是我的类模板)
<?php echo '<?php'; ?>
namespace Model\Base;
use Model\Model;
class <?php echo ucfirst(camel_case($table->TABLE_NAME));?> extends Model {
/**
* @var String
*/
protected $table = '<?php echo $table->TABLE_NAME;?>';
<?php if (isset($meta['pk'])):?>
/**
* @var String
*/
protected $primaryKey = '<?php echo $meta['pk'];?>';
/**
* attributes not writable from outside
* @var mixed
*/
protected $guarded = array('<?php echo $meta['pk'];?>');
<?php endif;?>
/**
* Timestamps we dont want here
* @var Boolean
*/
public $timestamps = false;
<?php if (isset($meta['fk'])):?>
<?php foreach($meta['fk'] as $keys):?>
/**
* @return HasOne
*/
public function <?php echo camel_case($keys['refTable']);?>()
{
return $this->hasOne('Model\<?php echo ucfirst(camel_case($keys['refTable']));?>', '<?php echo $keys['refColumn'];?>', '<?php echo $keys['column'];?>');
}
<?php endforeach;?>
<?php endif;?>
}
然后简单地通过给它文件夹来生成你的基类:(从你喜欢的任何地方)
$controller = new \Admin\ModelController();
$controller->create(__DIR__ . DIRECTORY_SEPARATOR . 'tmpModel');
这给了我一些不错的方法来让我的基类自动生成我需要的方式。请记住,您必须能够与您的 db 用户一起查看 information_schema 模式。
希望这可以帮助