gpt4 book ai didi

php - 如何在 Laravel 模型中编写 NotMapped 实体?

转载 作者:可可西里 更新时间:2023-11-01 12:53:04 27 4
gpt4 key购买 nike

我是 laravel 的新手,因此我的问题对某些人来说可能很奇怪。好吧,我的问题是如何在 Laravel Model 类中编写一个实体,该实体在迁移后不会在数据库中创建任何字段。例如

class JobseekerModel extends Model
{
use SoftDeletes;
protected $table='dbl_jobseekers';
protected $primaryKey='id';
protected $fillable=[
'FirstName',
'MiddleName',
'LastName',
'Dob',
'Education',
'DesireField',
'Skill',
'SpecialSkill',
'Experience',
'Location',
'HomeAddress',
'Salary',
'Comenteries',
'Resume'
];
protected $dates = ['deleted_at'];
}

这是我的模型,现在我想在我的模型中添加另一个名为“PagedListSize”的属性,但我不想将其创建为数据库列。那么我该怎么做呢?

例如,我熟悉在 .Net Framework 中使用 NotMapped 属性,它的写法如下

[NotMapped]
public int PagedListSize {set; get;}

那么,我该如何做到这一点。有没有办法在 laravel 中做到这一点?我正在开发 Laravel 5.4

最佳答案

您可以创建自定义 Mutators拥有那种自定义属性,无需将它们映射到 Laravel 中的数据库字段。

class Tag extends Model
{
public function getFullNameAttribute()
{
return $this->first_name.' '.$this->last_name;
}

public function setFullNameAttribute($value)
{
list($this->first_name, $this->last_name) = explode(' ', $value);
}
}

然后你可以在初始化模型后像这样使用它:

$tag->full_name = "Christos Lytras";
echo $tag->first_name; // prints "Christos"
echo $tag->last_name; // prints "Lytras"

这是修补匠的截图:

Artisan Tinker Example

关于php - 如何在 Laravel 模型中编写 NotMapped 实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43820022/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com