检查 Laravel 模型表中是否存在列,然后应用条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51703381/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:57:46  来源:igfitidea点击:

Check if column exist in Laravel model's table and then apply condition

phplaravellaravel-5eloquent

提问by Niklesh Raut

Current Situation: We are creating new database for new registration.

当前情况:我们正在为新注册创建新数据库。

Problem: If any changes done in database migration we need to handle it for previously created database. Or run that migration for each previously created database.

问题:如果在数据库迁移中进行了任何更改,我们需要为以前创建的数据库处理它。或者为每个以前创建的数据库运行该迁移。

If we run migration for each database no problem.

如果我们为每个数据库运行迁移没问题。

Question: how to check database table has column for which we are applying condition in query.

问题:如何检查数据库表是否有我们在查询中应用条件的列。

Currently I need to fire two queries first for first row and check the existence of that column and then apply condition in where clause. like below

目前我需要首先为第一行触发两个查询并检查该列是否存在,然后在 where 子句中应用条件。像下面

$firstRow = Model::first();
if(isset($firstRow->is_splited)){
    $records = Model::where('is_splited',0)->get(); // this will give error if I don't check column existence for previously created database. 
}else{
    $records = Model::all();
}

Is there any way to achieve in one query. Or any better way to do it ?

有什么办法可以在一个查询中实现。或者有什么更好的方法来做到这一点?



Thanks for your time and suggestion.

感谢您的时间和建议。

回答by Niklesh Raut

@DigitalDrifter gave an idea to use Schemaclass so I just tried like this

@DigitalDrifter 提出了一个使用Schema类的想法,所以我只是尝试这样

I Include Schemaclass

我包括Schema

use Illuminate\Support\Facades\Schema;

And check column by using Schemaclass, and it also works

并通过使用Schema类检查列,它也有效

$isColExist = Schema::connection("connection_name")->hasColumn('table_name','is_splited');
$q = Acquire::with("block");
if($isColExist){
    $q->where('is_splited',0);
}
$records = $q->get();

回答by DigitalDrifter

You can do the following to get an array of Column classes:

您可以执行以下操作来获取 Column 类的数组:

$columns = $model->getConnection()->getDoctrineSchemaManager()->getColumns();

There's also getColumnListingand hasColumn.

还有getColumnListinghasColumn

回答by wheelmaker

Updated solution working in 5.8

在 5.8 中工作的更新解决方案

if ($object->getConnection()
           ->getSchemaBuilder()
           ->hasColumn($object->getTable(), 'column_name')) {
    // required update here
}

This solution only requires an $object and a 'column_name' to work. The connection and table names are derived from the object itself.

此解决方案只需要 $object 和 'column_name' 即可工作。连接和表名是从对象本身派生的。