php Laravel Eloquent 模型属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23396138/
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
Laravel Eloquent Model Attributes
提问by mattcrowe
After instantiating a model class that extends Laravel's Eloquent Model class, is there a way to determine if the property/attribute maps to the table, and therefore can be saved to the table?
在实例化一个扩展 Laravel 的 Eloquent Model 类的模型类之后,有没有办法确定属性/属性是否映射到表,从而可以保存到表中?
For example, I have a table announcements
with columns id
, text
and "created_by".
例如,我有一个表announcements
的列id
,text
而“CREATED_BY”。
How can I know created_by
is an attribute and will be saved if set?
我怎么知道created_by
是一个属性,如果设置将被保存?
$announcement = new Announcement();
isset($announcement->created_by)
understandably returns false if I haven't explicitly set the value yet. I have tried various functions inherited from the Eloquent model class, but so far none have worked. I'm looking for something like:
isset($announcement->created_by)
如果我尚未明确设置该值,则可以理解地返回 false。我尝试了从 Eloquent 模型类继承的各种函数,但到目前为止都没有奏效。我正在寻找类似的东西:
$announcement->doesThisMapToMyTable('created_by')
that returns true whether or not $announcement->created_by
has been set.
$announcement->doesThisMapToMyTable('created_by')
无论是否$announcement->created_by
设置,都返回 true 。
采纳答案by mindsupport
For Laravel 5.4:
对于 Laravel 5.4:
$hasCreatedAt = \Schema::hasColumn(app(Model::class)->getTable(), 'created_at');
if($hasCreatedAt == true) {
...
}
回答by Antonio Carlos Ribeiro
If your model is filled with data, you can:
如果您的模型充满数据,您可以:
$announcement = Announcement::find(1);
$attributes = $announcement->getAttributes();
isset($attributes['created_by']);
For empty models (new Models), unfortunately you will have to get the columns using a small hack. Add this method to your BaseModel:
对于空模型(新模型),不幸的是,您必须使用一个小技巧来获取列。将此方法添加到您的 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;
}
}
Extend your model from it:
从中扩展您的模型:
class Announcement extends BaseModel {
}
Then you will be able to:
然后你将能够:
$columns = $announcement->getAllColumnsNames();
isset($columns['created_by']);
回答by Leith
Rather than writing your own lookup into the database internals, you can just use the Schema
facadeto look up the columns:
无需将自己的查找写入数据库内部,您只需使用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
}
回答by Janne
Laravel 5.4
Laravel 5.4
I used Leiths answer to create generic helper method, which automatically maps JS-object to Laravel model (and basically ignores those properties which are not part of model, thus avoiding QueryBuilder error messages for undefined columns). Additionally contains simple createOrEdit -approach (even though doesn't have "does ID exist?" -validation):
我使用 Leiths answer 创建通用辅助方法,该方法自动将 JS 对象映射到 Laravel 模型(并且基本上忽略了那些不属于模型的属性,从而避免了未定义列的 QueryBuilder 错误消息)。此外还包含简单的 createOrEdit -方法(即使没有“ID 是否存在?” -validation):
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;
}
回答by morawcik
I used to !empty($announcement->created_by)
and it's work great for my
我曾经这样做过!empty($announcement->created_by)
,这对我来说非常有用