使用 Laravel 检查数据库是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29535229/
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 database if exists using Laravel
提问by Richard Hewitt
I am trying to write a changelog using Laravel and have been asked to pull data from a MySQL database into an array; check in the array, if an account ID exists based on values read in from JSON files.
我正在尝试使用 Laravel 编写变更日志,并被要求将数据从 MySQL 数据库中提取到数组中;检查数组,如果根据从 JSON 文件中读取的值存在帐户 ID。
If not present, I need to create it and add to the array.
如果不存在,我需要创建它并添加到数组中。
The code I have at the moment adds entries to the database, but it does not do any sort of checking; my code is as follows:
我目前的代码向数据库添加了条目,但它不做任何检查;我的代码如下:
if(isset($cfi->awsAccountId)) {
$aid= new Account;
$aid->aws_account_id = $cfi->awsAccountId;
$aid->save();
}
回答by Learner
if anyone is still interested, it can be done as follows:
如果有人仍然感兴趣,可以按如下方式进行:
Demo controller code:
演示控制器代码:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
class Testing extends Controller
{
public function get()
{
$query = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?";
$db = DB::select($query, [$your_database_name]);
if (empty($db)) {
echo 'No db exist of that name!';
} else {
echo 'db already exists!';
}
}
}