简体   繁体   English

Laravel 模型 - 如果数据库表不存在则返回 null

[英]Laravel model - return null if the DB table doesn't exist

When I create a model, I want to check if the table exists in the DB.创建模型时,我想检查该表是否存在于数据库中。 If it doesn't then I want to return a null.如果不是,那么我想返回一个空值。 This is to prevent a record insert if the table doesn't exist yet.这是为了防止在表尚不存在时插入记录。

In my model I have tried this.在我的模型中,我已经尝试过这个。 The Schema call returns false, but I'm still getting a model returned and not a null. Schema 调用返回 false,但我仍然返回模型而不是 null。

class SomeDataTable extends Model
{
  public function __construct($id)
  {
    $this->setTable($id);
    if (Schema::connection($this->connection)->hasTable($this->table) === false) {
      return null;
    }else{
      parent::__construct();
    }
  }

  public function setTable($id)
  {
    $this->table = $id.'_some_data_table';
  }
}

I'm not sure if you're looking for an ubiquitous solution.我不确定您是否正在寻找无处不在的解决方案。 But what I'd do is do php aritsan migrate -m in the terminal to run migrations of all models.但是我要做的是在终端中执行php aritsan migrate -m以运行所有模型的迁移。 That way, all model tables are created by default.这样,默认情况下会创建所有模型表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 laravel 中返回多对多关系结果,如果不存在则返回 null - return many to many relation result in laravel and return null if it doesn't exist 未捕获的 TYPO3 异常:#1472074485:表 'db.tx_sfregister_domain_model_frontenduser' 不存在...? - Uncaught TYPO3 Exception: #1472074485: Table 'db.tx_sfregister_domain_model_frontenduser' doesn't exist…? Laravel 迁移不会在数据库中添加表 - Laravel migration doesn't add table in DB SQLSTATE[42S02]:未找到基表或视图:1146 Laravel 5.2 上不存在表“db_wls.users” - SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db_wls.users' doesn't exist on laravel 5.2 在Laravel 3中,带有自定义表的模型无法保存 - Model with custom table doesn't save, in Laravel 3 用户模型中不存在最新的 Laravel 刀片方法 - Laravel blade method latest doesn´t exist on user model Laravel-如果模型/行不存在或被软删除,则显示异常 - Laravel - show exception if model/row doesn't exist or soft deleted zend db select table不存在错误 - zend db select table doesn't exist error Laravel 奇怪的问题:使用 DB::table() 查询返回数据,但不使用 model:: - Laravel weird issue: query return data with DB::table() but not with model:: Laravel 6 数据库种子问题:表不存在 - Laravel 6 Database Seed problem: Table doesn't exist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM