如何检查 laravel 中是否存在多列?

How do i check existence of multiple columns in laravel?

我尝试通过放置一个强制列数组来使用 hasColumn(),但是数组作为参数抛出了这个错误:

(1/1) ErrorException strtolower() expects parameter 1 to be string, array given

这是我的代码:

if (Schema::hasColumn('table_name', ['id', 'name'])){
  //
}

根据官方 Laracel 文档,您无法将数组作为参数。因此,您会收到此错误。

这是语法:

Schema::hasColumn({TABLE NAME}, {COLUMN NAME})

所以在你的情况下这将是:

if (Schema::hasColumn('table_name', 'id') && Schema::hasColumn('table_name', 'name'))
{
    //
}

在 Laravel 8+ 中,更简洁的解决方案是使用此架构函数

@param string $table
@param array $columns
@return bool    
public static function hasColumns($table, $columns) { }

所以你问题中的函数应该是这样的:

if (Schema::hasColumns('table_name', ['id', 'name'])){
  //
}