[英]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.