我正在尝试创建REST Api并解决这个恼人的问题。我正在使用odoo数据库中的现有表,该数据库预先插入了几个记录。我意识到每当我想从odoo中检索现有行时,就会出现“碳尾随数据”错误。但不是我通过laravel雄辩的方法创造的记录。
我已经将日期mutator和cast timestamp mutator定义为模型中表的正确字段。但它仍然没有让我到任何地方。除了更新/删除现有记录的日期/时间戳值之外,还有其他方法吗?
这是我的一些代码
模型
namespace App;
use App\Scopes\ActiveScope;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'hr_employee';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
// Private information
'resource_id',
'name',
'user_id',
'active',
'address_home_id',
'country_id',
'gender',
'marital',
'spouse_complete_name',
'spouse_birthday',
'children',
'place_of_birth',
'country_of_birth',
'birthday',
'emergency_contact',
'emergency_phone',
'identification_id',
'passport_id',
'bank_account_id',
'permit_no',
'visa_no',
'visa_expire',
'additional_info',
'km_home_work',
'google_drive_link',
'certificate',
'study_field',
'study_school',
// Work information
'company_id',
'resource_calendar_id',
'department_id',
'job_id',
'job_title',
'work_phone',
'mobile_phone',
'work_email',
'work_location',
'notes',
'parent_id',
'coach_id',
'barcode',
'pin',
'color',
'last_attendance_id',
'create_uid',
'create_date',
'write_uid',
'write_date',
];
const CREATED_AT = 'create_date';
const UPDATED_AT = 'write_date';
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = [
'birthday',
'spouse_birthdate',
'visa_expire',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'create_date' => 'timestamp',
'write_date' => 'timestamp',
];
public function Job() {
return $this->belongsTo('App\Job', 'job_id');
}
public function getNameAcronymAttribute() {
$words = explode(" ", $this->name);
$acronym = "";
foreach ($words as $w) {
$acronym .= $w[0];
}
return $acronym;
}
}
控制器显示动作
public function show($id)
{
$httpCode = 200;
$message = "Here is the employee data";
$modelData = null;
try {
$modelData = Employee::find($id);
if (!$modelData) {
$httpCode = 404;
$message = 'Employee data not found';
}
} catch (Exception $e) {
$httpCode = $e->getCode();
$message = $e->getMessage();
}
return response()->json([
'message' => $message,
'modelData' => $modelData
], $httpCode);
}
在$dates
数组中指定列时,laravel会将这些列的值转换为Carbon
实例。对于created_at
和updated_at
列,默认情况也是如此。
因此,以下所有列都必须是有效的时间戳列:
protected $dates = [
'birthday',
'spouse_birthdate',
'visa_expire',
];
如果您的列不是时间戳,则可以使用casting
:
protected $casts = [
'birthday' => 'date:Y-m-d',
'spouse_birthdate' => 'date:Y-m-d'
];
您尚未显示任何代码。但实际上,根据我过去的经验,昨天有同样的问题,首先,使用碳解析创建日期的碳实例,以便在日期挂钩任何其他碳辅助方法。说你有一个像= $date = 2019-02-14
的日期
现在可以这样做:
$d = Carbon::parse($date);
//hook any further carbon helper methods on the $d variable and it should work