Laravel 雄辩的模型属性

2022-08-30 19:40:08

在实例化扩展了 Laravel 的 Eloquent Model 类的模型类之后,有没有办法确定属性/属性是否映射到表,从而可以保存到表中?

例如,我有一个包含列和“created_by”的表。announcementsidtext

我如何知道是属性,如果设置了属性,将保存?created_by

$announcement = new Announcement();

isset($announcement->created_by)如果我还没有显式设置值,可以理解地返回false。我已经尝试了从 Eloquent 模型类继承的各种函数,但到目前为止,还没有一个函数起作用。我正在寻找类似的东西:

$announcement->doesThisMapToMyTable('created_by')无论是否已设置,都返回 true。$announcement->created_by


答案 1

如果您的模型填充了数据,您可以:

$announcement = Announcement::find(1);

$attributes = $announcement->getAttributes();

isset($attributes['created_by']);

对于空模型(新模型),不幸的是,您将不得不使用一个小的黑客来获取列。将此方法添加到基本模型:

<?php

class BaseModel extends Eloquent {

    public function getAllColumnsNames()
    {
        switch (DB::connection()->getConfig('driver')) {
            case 'pgsql':
                $query = "SELECT column_name FROM information_schema.columns WHERE table_name = '".$this->getTable()."'";
                $column_name = 'column_name';
                $reverse = true;
                break;

            case 'mysql':
                $query = 'SHOW COLUMNS FROM '.$this->getTable();
                $column_name = 'Field';
                $reverse = false;
                break;

            case 'sqlsrv':
                $parts = explode('.', $this->getTable());
                $num = (count($parts) - 1);
                $table = $parts[$num];
                $query = "SELECT column_name FROM ".DB::connection()->getConfig('database').".INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'".$table."'";
                $column_name = 'column_name';
                $reverse = false;
                break;

            default: 
                $error = 'Database driver not supported: '.DB::connection()->getConfig('driver');
                throw new Exception($error);
                break;
        }

        $columns = array();

        foreach(DB::select($query) as $column)
        {
            $columns[$column->$column_name] = $column->$column_name; // setting the column name as key too
        }

        if($reverse)
        {
            $columns = array_reverse($columns);
        }

        return $columns;
    }

}

从中扩展模型:

class Announcement extends BaseModel {

}

然后,您将能够:

$columns = $announcement->getAllColumnsNames();

isset($columns['created_by']);

答案 2

无需将自己的查找写入数据库内部,只需使用 Schema 外观来查找列:

use Illuminate\Support\Facades\Schema;

$announcement = new Announcement();
$column_names = Schema::getColumnListing($announcement->getTable());
if (in_array('created_by', $column_names)) {
  // whatever you need
}

或者,早在Laravel 4就有检查:hasColumn()

use Illuminate\Support\Facades\Schema;

$announcement = new Announcement();
if (Schema::hasColumn($announcement->getTable(), 'created_by')) {
  // whatever you need
}

推荐