模型工厂就像这样返回基于生日的年龄

问题描述 投票:-1回答:2

enter image description here

我想写一个引用该生日条目的函数..

到目前为止,这就是我所做的

但我进入终端enter image description here

php laravel factory faker
2个回答
0
投票

我们可以使用下面的代码。

$birthDate = '31-07-1983';
$data = [
    'age'=> call_user_func(function() use( $birthDate){
        return (date('Y') - date('Y', strtotime($birthDate)));
    })
];
print_r($data);

0
投票

考虑到age是一个计算字段并且每天都会更改,这不应该是存储在数据库中的数据,因此不应该在您的工厂中。

我将从数据库和工厂中删除该字段,并将accessor添加到您的模型中:

// Make sure birthdate is cast to a Carbon date.
protected $dates = [
    'birthdate',
];

// Define the "age" property accessor.
public function getAgeAttribute()
{
    return now()->diffInYears($this->birthdate);
}

使用访问者,您可以作为属性访问该字段:

$ci = App\CriminalInfo::find(1);
dd($ci->age);

如果你想在模型的数组/ json输出中看到它,你也可以将它添加到$appends property

© www.soinside.com 2019 - 2024. All rights reserved.