2017-05-25 138 views
0

我正在開發我的第一個Laravel項目,並且我想創建一個REST Api框架以便與AngularJS一起使用它。在我的系統中,我有兩種類型的用戶:用戶A用戶B。我想使用默認的Laravel用戶表來處理身份驗證,並創建另外兩個表usera和userb,每個表都有一個列user_id這是用戶表的外鍵。從Laravel的一對一關係表中獲取數據

我將只使用usera表來解釋我的問題。我的遷移是喜歡它:

用戶表

//users table migration 
     class CreateUsersTable extends Migration 
     { 
      public function up() 
      { 
       Schema::create('users', function (Blueprint $table) { 
        $table->increments('id'); 
        $table->string('name'); 
        $table->string('email')->unique(); 
        $table->string('password'); 
        $table->rememberToken(); 
        $table->timestamps(); 
       }); 
      } 
    ... 
     } 

的用戶A表

class CreateUserA extends Migration 
    { 
     public function up() 
     { 
      Schema::create('usera', function(Blueprint $table){ 
       $table->increments('id'); 
       $table->string('document_number') 
       $table->integer('user_id')->unsigned(); 
       $table->foreign('user_id') 
        ->references('id') 
        ->on('users') 
        ->onDelete('cascade'); 
       $table->timestamps(); 
      }); 
     } 
     ... 
    } 

在用戶A的模型類,我做到了:

class UserA extends Model 
{ 
    protected $fillable = array('id', 'document_number', 'user_id'); 
    protected $hidden = array('created_at', 'updated_at'); 

    public function user(){ 
     $this->belongsTo('App\User'); 
    } 
} 

所以,我創建了一個UsersA控制器與API方法配合使用,並配置路由以訪問相應的功能。通過獲得「API/usersa /」網址是重定向到我的控制器的指數函數,函數就是這樣:

public function index($id = null) { 
    if ($id == null) { 
     return UserA::orderBy('id', 'asc')->get(); 
    }else{ 
     return Usuario::find($id); 
    } 
} 

有了這個,我可以得到usersa表中的數據,但我想合併用戶和用戶表,並得到類似這樣的迴應:

[ 
    { 
     'id': 1, 
     'name': 'foo', 
     'email': '[email protected]', 
     'document_number': '1234' 
    } 
] 

我該如何做到這一點?

回答

1

它是否必須像這樣平坦?最簡單的解決方法是:

public function index($id = null) { 
    if ($id == null) { 
     return UserA::with('user')->orderBy('id', 'asc')->get(); 
    }else{ 
     return Usuario::with('usera')->find($id); // or whatever the relation name is. 
    } 
} 
+0

我試了一下前問在這裏,但它觸發一個例外:'調用未定義的關係[用戶]型號[應用\\用戶A] .' 我以爲只有創建外鍵框架將「理解」關係。我需要做更多的事情? –

+0

關係是'user' not'users' –

+0

是的,你是對的!現在工作。我知道應該有db表 –