从Laravel中的一对一关系表中获取数据

时间:2017-05-25 18:07:41

标签: laravel rest api one-to-one

我正在开发我的第一个Laravel项目,我想用框架创建一个REST Api来使用AngularJS。在我的系统中,我有两种类型的用户:用户A 用户B 。我想使用默认的Laravel用户表来处理身份验证,并创建另外两个表,usera和userb,每个表都有一列 user_id ,这是用户的外键表

我只使用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();
                });
            }
    ...
        }

用户表

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

在UserA模型类中,我做到了:

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

因此,我使用API​​方法创建了一个UsersA控制器,并配置了访问相应功能的路由。 ' api / usersa /'通过GET的url重定向到我的控制器的索引函数,函数是这样的:

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': 'foo@bar.com',
      'document_number': '1234'
   }
]

我怎么能这样做?

1 个答案:

答案 0 :(得分: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.
    }
}
相关问题