【问题标题】:Laravel: Getting 'SQLSTATE[HY000]: General error: 1 no such table: webServiceLogs' when trying to store in databaseLaravel:获取\'SQLSTATE [HY000]:一般错误:1没有这样的表:webServiceLogs \'尝试存储在数据库中
【发布时间】:2022-10-23 21:49:20
【问题描述】:

我已经设置了一个迁移文件:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class LogggingTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::connection('mysql2')->create('webServiceLogs', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->timestamps();
        $table->string('query');
        $table->string('response');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('webServiceLogs');
}
}

还有一个模型:

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class WebServiceLog extends Model
{
    use HasFactory;

    protected $table = 'webServiceLogs';

}

这是保存数据的控制器功能:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\WebServiceLog;
use Illuminate\Foundation\Testing\RefreshDatabase;

class LoggingController extends Controller
{
/**
 * Log WS requests.
 *
 * @return \Illuminate\Http\Response
 */
public function LogWebService($url, $data)
{
    $web_service_log = new WebServiceLog();

    $web_service_log->query    = json_encode($url, true);
    $web_service_log->response = json_encode($data ,true);

    $web_service_log->save();
}
}

当我迁移时,表是在 phpmyadmin 中创建的,但是当我在表单中运行“LogWebService”函数时,我收到此错误,即使该表存在于 phpmyadmin 中:

SQLSTATE [HY000]:一般错误:1没有这样的表:webServiceLogs

【问题讨论】:

  • 将迁移的名称从 LoggingTable 更改为 CreateWebServiceLogsTable,因为这遵循 laravel 迁移的标准命名,这可能会导致您的问题。此外,表的标准命名不是驼峰式命名,因此我建议将迁​​移重命名为 web_service_logs。
  • 这回答了你的问题了吗? How to use multiple databases in Laravel

标签: laravel model migration


【解决方案1】:

在您的迁移中,您更改了连接,您只是在模型中丢失了它

WebServiceLog extends Model
{
    use HasFactory;

    protected $connection= 'mysql2';

    protected $table = 'webServiceLogs';
}

【讨论】:

    【解决方案2】:

    解决:

    我正在使用多个数据库(sqlite 和 mysql)。在 database.php 中我更新了:

    'default' => env('DB_CONNECTION', 'mysql'),
    

    至:

    'default' => 'mysql2',
    

    【讨论】:

      猜你喜欢
      • 2021-09-19
      • 2018-10-29
      • 1970-01-01
      • 2018-05-29
      • 2021-09-10
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多