php - Laravel 定义 Mutator

标签 php mysql laravel

<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class UserInformation extends Model {

    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = "user_information";

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'first_name',
        'last_name',
        'img_path',
        'born',
        'gender',
        'address',
        'country_id',
        'about',
        'institution',
        'area_of_expertise',
        'cv_path',
        'facebook',
        'twitter',
        'instagram',
        'linkedin',
        'university',
        'university_graduated_at',
        'md',
        'md_graduated_at',
        'associate_professor',
        'associate_professor_graduated_at'
    ];

    public function setBornAttribute($date) {
        $this->attributes['born'] = Carbon::createFromFormat('Y-m-d', $date);
    }

    public function users() {
        return $this->belongsTo('App\User', 'user_id', 'id');
    }
}

错误:

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '26/10/1988' for column 'born' at row 1 (SQL: update user_information

如何更新:

public function updateUser($request, $id) {
        $user = User::with('userInformation')->findOrFail($id);
        $user->update(array_filter($request->all()));
        $user->userInformation()->update(array_filter($request->only([
            'title',
            'first_name',
            'last_name',
            'img_path',
            'born',
            'gender',
            'address',
            'country_id',
            'about',
            'institution',
            'area_of_expertise',
            'cv_path',
            'facebook',
            'twitter',
            'instagram',
            'linkedin',
            'university',
            'university_graduated_at',
            'md',
            'md_graduated_at',
            'associate_professor',
            'associate_professor_graduated_at'
        ]), 'strlen'));

        return User::with('userInformation')->findOrFail($id);
    }

我从用户界面发送出生日期 d/m/Y 格式。当我将这些数据存储在 mysql 中时,我必须重新格式化为 Y-m-d..

我用谷歌搜索并找到了更改器(mutator): https://laravel.com/docs/5.3/eloquent-mutators

我将 setNameAttribute 函数添加到 UserInformation 模型中。我刷新了页面然后再次尝试。但一切都没有改变。我也遇到同样的错误。

如何解决这个问题?

附: :我使用的是 Laravel 5.3

最佳答案

使用碳解析

public function setBornAttribute($value)
{
    $this->attributes['born'] = Carbon::parse($value);
}

关于php - Laravel 定义 Mutator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44178588/

相关文章:

php - 如何以一致的方式加密主 key

php - 为什么删除按钮会使编辑按钮执行无效

mysql - 从表中获取列值作为 sql 查询结果中的键

php - 加载文件中的数据给我一个访问被拒绝的权限错误。我还能如何将文本文件导入数据库中的表中?

Laravel Lighthouse 分页字段结果

php - 使用 PHP 将 TXT 文件中的行插入 SQL 数据库

php - for循环中的if语句只执行一次

mysql - 在没有where条件的情况下通过循环更新列值

mysql - SQL 查询将我的数字返回为字符串而不是整数

Laravel FFMPEG 视频转换无需等待队列