如何在 Laravel 架构生成器中传递变量
How to pass variable inside Laravel Schema builder
我无法使以下 Laravel 代码正常工作。我正在尝试以下代码。这是 table 列数组:
$cols = array(
'inc' => array('id'),
'str' => array(
'name',
'email',
'password'
),
...
);
函数如下:
private function addCols($tableName, $cols){
foreach ($cols as $k => $type) {
foreach ($cols[$k] as $col) {
if(!Schema::hasColumn($tableName, $col)){
Schema::table($tableName, function($table)
{
// Problem here $k and $col are `Undefined`
}
// Outside here $k and $col have values like `str`, `name`
}
}
}
}
我不太擅长PHP。
use
关键字就是您要查找的内容。它有助于匿名函数 "inherit" 现有变量,否则这些变量将超出其范围:
Schema::table($tableName, function($table) use ($k, $col)
{
// $k and $col are now defined
}
这是文档:
http://php.net/manual/en/functions.anonymous.php#example-186
你也可以用
public function addColumnTable($table_name,$field_name,$field_type){
Schema::table($table_name, function (Blueprint $table) use($field_name,$field_type) {
$table->{$field_type}($field_name);
});
}
我无法使以下 Laravel 代码正常工作。我正在尝试以下代码。这是 table 列数组:
$cols = array(
'inc' => array('id'),
'str' => array(
'name',
'email',
'password'
),
...
);
函数如下:
private function addCols($tableName, $cols){
foreach ($cols as $k => $type) {
foreach ($cols[$k] as $col) {
if(!Schema::hasColumn($tableName, $col)){
Schema::table($tableName, function($table)
{
// Problem here $k and $col are `Undefined`
}
// Outside here $k and $col have values like `str`, `name`
}
}
}
}
我不太擅长PHP。
use
关键字就是您要查找的内容。它有助于匿名函数 "inherit" 现有变量,否则这些变量将超出其范围:
Schema::table($tableName, function($table) use ($k, $col)
{
// $k and $col are now defined
}
这是文档: http://php.net/manual/en/functions.anonymous.php#example-186
你也可以用
public function addColumnTable($table_name,$field_name,$field_type){
Schema::table($table_name, function (Blueprint $table) use($field_name,$field_type) {
$table->{$field_type}($field_name);
});
}