检查 Laravel 中是否存在唯一索引键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30504939/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a unique index key exists in Laravel
提问by Luís Cruz
The Schema\Builderclass has a hasTable()
and hasColumn()
methods to check the existence of a table and a column, respectively.
该架构\生成器类有一个hasTable()
和hasColumn()
方法来检查一个表和一个柱的存在,分别。
Is there any method or way to check if an index key (such as a unique key) exists?
是否有任何方法或方法可以检查索引键(例如唯一键)是否存在?
回答by Luís Cruz
While Laravel doesn't provide any method to check the existence of a key, you could use any of the available queries in MySQLand then use DB::select()
.
虽然 Laravel 没有提供任何方法来检查密钥是否存在,但您可以使用MySQL 中的任何可用查询,然后使用DB::select()
.
For instance:
例如:
$keyExists = DB::select(
DB::raw(
'SHOW KEYS
FROM your_table_name
WHERE Key_name=\'your_key_name\''
)
);
Just replace your_table_name
and your_key_name
for the correct values.
只需替换your_table_name
和your_key_name
以获得正确的值。
回答by Jean Paul Ruiz
If you are using Laravel then most likely you will have access to an ORM like Eloquent. Assuming you are using Eloquent, you might be able to do something like this:
如果您使用的是 Laravel,那么您很可能可以访问像 Eloquent 这样的 ORM。假设您正在使用 Eloquent,您可能可以执行以下操作:
try {
Schema::table(
'the_name_of_your_table',
function (Blueprint $table) {
$sm = Schema::getConnection()->getDoctrineSchemaManager();
$indexesFound = $sm->listTableIndexes('the_name_of_your_table');
$indexesToCheck = [
'index_name_1',
'index_name_2',
'index_name_3',
'index_name_4'
];
foreach ($indexesToCheck as $currentIndex) {
if (array_key_exists($currentIndex, $indexesFound)) {
// The current index exists in the table, do something here :)
}
}
}
);
} catch (Exception $e) {
}