Laravel Eloquent模型属性

时间:2014-04-30 19:08:06

标签: php laravel laravel-4

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

例如,我有一个表announcements,其中列idtext和" created_by"。

我怎么知道created_by是一个属性,如果设置将被保存?

$announcement = new Announcement();
如果我还没有明确设置该值,那么

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

无论$announcement->doesThisMapToMyTable('created_by')是否已设置,

$announcement->created_by都会返回true。

5 个答案:

答案 0 :(得分:25)

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

$announcement = Announcement::find(1);

$attributes = $announcement->getAttributes();

isset($attributes['created_by']);

对于空模型(新模型),遗憾的是,您必须使用小型黑客获取列。将此方法添加到BaseModel:

<?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']);

答案 1 :(得分:7)

您可以使用Schema facade查找列,而不是将自己的查找编写到数据库内部:

use Illuminate\Support\Facades\Schema;

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

答案 2 :(得分:6)

对于Laravel 5.4:

$hasCreatedAt = \Schema::hasColumn(app(Model::class)->getTable(), 'created_at');

    if($hasCreatedAt == true) {
       ...
    }

答案 3 :(得分:0)

我曾经!empty($announcement->created_by),这对我的

非常有用

答案 4 :(得分:0)

Laravel 5.4

我使用Leiths的答案来创建通用辅助方法,它自动将JS-object映射到Laravel模型(并且基本上忽略了那些不属于模型的属性,从而避免了未定义列的QueryBuilder错误消息)。另外包含简单的createOrEdit -approach(尽管没有&#34; ID是否存在?&#34; -validation):

&#13;
&#13;
    public function store(Request $request) {
        if($request->input("club")) {
            $club = \App\Club::find($request->input("club")["id"]);
        } else {
            $club = new \App\Club;
        }
        $club = self::mapModel($request->input("club"), $club);
        $club->save();
    }
    
    public function mapModel($input,$model) {
        $columns = Schema::getColumnListing($model->getTable());
        foreach ($columns as $i => $key) {
            if($input[$key]) {
                $model->{$key} = $input[$key];
            }
        }
        return $model;
    }
&#13;
&#13;
&#13;