【问题标题】:How to write a NotMapped entity in Laravel Model?如何在 Laravel 模型中编写 NotMapped 实体?
【发布时间】:2017-10-04 19:48:40
【问题描述】:

我是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

【问题讨论】:

  • 你能说得更具体一点吗?你需要应该计算的字段吗?或者你需要一个类的简单属性?
  • 好吧,我需要一个类的简单属性,它不会在数据库中创建列。但是我将能够将数据从Controller 传递到viewviewController。我将仅使用此属性以用于某些计算目的。没有别的。
  • @lazycoder 在您的问题中,您在哪里声明需要序列化属性?因为接受的答案与我的唯一区别是它解释了在将类转换为 json 数据时如何序列化属性。

标签: php laravel-5 model eloquent


【解决方案1】:

你可以在 Laravel 模型中添加受保护的属性,只要它们不与字段名冲突就可以了。此外,在 Laravel 中,迁移决定的是数据库结构,而不是模型,因此您不必冒险自动创建字段(实际上,默认模型在没有开箱即用的属性的情况下工作)。

编辑:来自默认包 User.php 的示例

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
    * You can add some properties here
    * will require getter and/or setters
    * does not need to be fillable
    */
    protected $someLogicalProperty;

}

实际的db结构在迁移中定义(2014_10_12_000000_create_users_table.php):

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('email')->unique();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

如您所见,时间戳和令牌甚至没有在用户模型中列出。定义后的所有可填充对象都可以设置为用户对象的公共属性($user-&gt;name = 'Bob';,但您也可以将其作为参数传递给 create()/save() 继承方法)。 Laravel 中不直接访问实体,但这里有,如果需要可以进一步指定。

【讨论】:

    【解决方案2】:

    您可以创建自定义 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"
    

    这是一个修补截图:

    【讨论】:

      【解决方案3】:

      在 Laravel 中做到这一点的最佳方式确实是通过 custom Mutators。此外,mutators 可以配置为显示在模型的 json 或数组输出转储中。例如对于PagedListSize,我们可以:

      public functionGetPagedListSizeAttribute()
      {
          return #some evaluation;
      }
      
      protected $appends = array('pagedListSize');
      

      这样,pagedListSize 不仅可以直接作为字段使用,而且只要模型为 serialized 作为 Json 或 Array,也可以使用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-28
        相关资源
        最近更新 更多