2016-10-28 4 views
0

Laravel 5.2을 사용하고 있습니다.모델의 Laravel 5.2 질량 할당이 동적 테이블 이름과 작동하지 않습니다.

난 I 동적 table 이름을 설정하고 mass assignment (즉 create() 법)에 그 레코드를 삽입 할 모델 User있다. 내 코드는 다음과 같은

사용자 :

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 : 그것은 내가 $input에서 설정 한 각각의 컬럼의 모든 값을 삽입되지

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); 
} 

문제가 변하기 쉬운. 테이블 이름이 변경 또는

$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

이 setTable 메서드는 생성자가 호출 될 때만 호출되기 때문에 비 정적 호출에만 올바른 테이블 이름이 지정됩니다.

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

을 그리고 이것은하지 않습니다 : 따라서이 작동합니다

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

그래서 질문은 다음이된다 : 곳 조건 테이블 이름을 정의하려면? ,

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

이것에 대한 좋은 솔루션은 또한 특성을 이용하여 할 수있다 : 객체를 생성 할 때, 바인딩 이벤트 같은 것을 사용할 수 있습니다, 또는 당신은 당신의 생성자에서 제공하는 기능으로 getTable이() 함수를 오버라이드 (override) 할 수 부팅 할 때이 작업을 수행합니다.

행운을 빈다. 이것이 작동하는지 알려주세요.

업데이트

미안 해요, 내가 잘못했다. (

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

생성의 코드에 따르면

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

내가이 라인입니다, 원래 수정의 포인트가 작동하지 않는 생각 : 정적 create() 메소드는 실제로 모델을 구축 않습니다), $ attributes 변수도 함께 전달해야합니다.

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

응답 해 주셔서 감사합니다. 확인하고 알려 드리겠습니다. – Dev

+0

그것은 효과가있다. 고마워. – Dev

+0

다행이지만 도울 수는 있었지만 잘 설명하지 못했습니다. 업데이트 된 답변을 확인하십시오. –

관련 문제