Laravel 5.2模型中的质量分配不适用于动态表名

时间:2016-10-28 04:54:34

标签: laravel laravel-5.2 mass-assignment

我正在使用Laravel 5.2

我有一个模型User,我想在其中动态设置table名称,并使用mass assignment(即create()方法)将记录插入其中。我的代码是,

用户:

class User extends Authenticatable
{
    use SoftDeletes;
    use Notifiable;

    protected $table = 'users';

    public function __construct() {
        parent::__construct();
        if(\Session::has("organization_id")){
            $org_id = \Session::get("organization_id");
            $t= $org_id.'_users';
            $this->setTable($t);
        }
    }

    protected $fillable = ['auth0_user_id','username', 'email', 'password',
                            'user_type','first_name','middle_name',
                            'last_name','gender','address',
                            'state','city','country',
                            'post_code','phone','photo',
                            'birth_date','status','doctor_title',
                            'created_by','updated_by','isGuest',
                            'email_varify','confirmation_code', 'membership_code'
                            ];

    protected $hidden = ['password', 'remember_token'];

    protected $appends = ['full_name','name_with_title'];

    protected $dates = ['deleted_at'];
}

UserController中:

public function register(Request $request){
    $input = $request->all();
    $input['user_type']='patient';
    $input['password'] = \Hash::make($request->password);
    $input['isGuest']= '1';
    $input['status']= 'Incomplete';
    $input['username'] =  str_random(10);
    $input['confirmation_code']= str_random(30);
    $user = User::create($input);
}

问题是,它没有在$input变量中设置的相应列中插入任何值。

我已经使用

验证了表名是否已更改
$user->getTable();

似乎没问题。我得到了确切的表名。

如果我使用

dd ($user);

然后结果如下:

App\Models\User Object
(
    [table:protected] => 1_users
    [fillable:protected] => Array
        (
            [0] => auth0_user_id
            [1] => username
            [2] => email
            [3] => password
            [4] => user_type
            [5] => first_name
            [6] => middle_name
            [7] => last_name
            [8] => gender
            [9] => address
            [10] => state
            [11] => city
            [12] => country
            [13] => post_code
            [14] => phone
            [15] => photo
            [16] => birth_date
            [17] => status
            [18] => doctor_title
            [19] => created_by
            [20] => updated_by
            [21] => isGuest
            [22] => email_varify
            [23] => confirmation_code
            [24] => membership_code
        )

    [hidden:protected] => Array
        (
            [0] => password
            [1] => remember_token
        )

    [appends:protected] => Array
        (
            [0] => full_name
            [1] => name_with_title
        )

    [dates:protected] => Array
        (
            [0] => deleted_at
        )

    [connection:protected] => 
    [primaryKey:protected] => id
    [keyType:protected] => int
    [perPage:protected] => 15
    [incrementing] => 1
    [timestamps] => 1
    [attributes:protected] => Array
        (
            [updated_at] => 2016-10-27 05:53:17
            [created_at] => 2016-10-27 05:53:17
            [id] => 20
        )

    [original:protected] => Array
        (
            [updated_at] => 2016-10-27 05:53:17
            [created_at] => 2016-10-27 05:53:17
            [id] => 20
        )

    [relations:protected] => Array
        (
        )

    [visible:protected] => Array
        (
        )

    [guarded:protected] => Array
        (
            [0] => *
        )

    [dateFormat:protected] => 
    [casts:protected] => Array
        (
        )

    [touches:protected] => Array
        (
        )

    [observables:protected] => Array
        (
        )

    [with:protected] => Array
        (
        )

    [exists] => 1
    [wasRecentlyCreated] => 1
    [forceDeleting:protected] => 
)

在这里,您可能会发现表名已成功更改,但我在[attributes:protected][original:protected]中找不到任何列。

我也尝试过:

$user = new User(); 
$user->create($input); 

但似乎没有任何效果。

如果我使用,

$user = new User(); 
$user->email = $input['email']; 
$user->save()

然后它似乎工作正常,但为此我必须在许多地方更新我的代码。

任何质量分配解决方案?

1 个答案:

答案 0 :(得分:2)

关键在于,只有非静态调用才能具有正确的表名,因为只有在调用构造函数时才会调用此setTable方法。因此,这将有效:

$user = new User; // constructor is called
$user->someinfo = 'foo';
$user->save();

这不会:

User::create(['someinfo' => 'foo']); 
// constructor is not called here

那么问题就变成了:在哪里定义这个条件表名称?你可以在创建对象时使用类似事件绑定的东西,或者你可以使用构造函数中提供的函数覆盖getTable()函数:

// in your model
public function getTable() {
  if(\Session::has("organization_id")){
    $org_id = \Session::get("organization_id");
    return $orig_id . '_users';
  }
  return 'users';
}

一个很好的解决方案也可以使用特征,它在启动时执行此操作。

祝你好运!如果有效,请告诉我。

<强>更新

对不起,我错了。静态create()方法确实构造了Model:

public static function create(array $attributes = [])
{
    $model = new static($attributes);
    $model->save();
    return $model;
}

我认为原始修复的重点不起作用,这些是:

public function __construct() {
  parent::__construct();

根据create()的代码,您还应该通过$ attributes变量:

public function __construct(array $attributes = []) {
  parent::__construct($attributes);
  // here your original setTable() code