2016-10-02 4 views
0

저는 전문 프로그래머가 아니므로 잘 설명하고 있는지 모르겠습니다.Laravel 모델 : 인스턴스 또는 관계?

웅변 관계는 문법과 기능 등이 모델 뒤에 등 ... - >belongsTo..

로, 내 데이터베이스에서 테이블입니다를 사용하여 모델에서 설정됩니다.

내 (laravel) 응용 프로그램에는 다른 사용자에 대한 특정 정보가 필요한 로그인 한 사용자가 있습니다. 하루가 끝나면 이들은 모두 사용자 일 뿐이며 사용자의 테이블에 머물러 있습니다.

그래서 다른 객체 (예 : 자동차)와 관계를 사용하면 모두 좋다. 다른 사용자와 관계를 맺으려고하면 오류가 발생합니다. Cannot redeclare class App\Models\User.

나는 여기에서 뭔가 잘못 생각하고 있습니다.

어쩌면 내가 '내 관리자'와 같은 다른 버전의 사용자를 '인스턴스화'해야한다는 느낌이 들지만 ... 정말로 필요합니까? 그것은 무엇보다도 조회수가 많습니다. 나는 그걸하는 법을 알 수 있을지 잘 모르겠다.

일부 안내해주세요.

+0

몇 가지 코드를 제공해 주시겠습니까? 분명히 User 클래스의 선언이 두 개 이상 있습니다. –

답변

0

당신은 두 가지 "사용자"모델을 만든 것 같은데 :

// /app/User.php: 

<?php namespace App; 
use Illuminate\Database\Eloquent\Model; 
class User extends Model 
{ 
    // ... 
    public function parent() { 
     return $this->belongsTo('App\User'); 
    } 

    public function children() { 
     return $this->hasMany('App\User'); 
    } 
} 

그런 다음 데이터베이스에 있는지 확인하십시오 대신 자체에 속하는 하나의 클래스를 갖고 싶어

// /app/User.php: 

<?php namespace App; 
use Illuminate\Database\Eloquent\Model; 
class User extends Model 
{ 
    // ... 
    public function user() { 
     return $this->hasOne('App\Models\User'); 
    } 
} 


// /app/models/User.php: 

<?php namespace App\Models; 
use Illuminate\Database\Eloquent\Model; 
class User extends Model 
{ 
    // ... 
    public function user() { 
     return $this->belongsTo('App\User'); 
    } 
} 

을 사용자 테이블에 user_id 속성이 있습니다 (database/migrations/2014_10_12_000000_create_users_table.php).

$table->integer('user_id')->unsigned()->nullable(); 
$table->foreign('user_id')->references('id')->on('users'); 

이제 사용자를 서로 연결할 수 있습니다.

<?php 

$manager = new User(); 
$employeeOne = new User(); 
$employeeTwo = new User(); 

$manager->children()->saveMany([ 
    $employeeOne, 
    $employeeTwo 
]); 

dd($employeeTwo->parent->name); // Manager's name