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'
}
]
我该如何做到这一点?
我试了一下前问在这里,但它触发一个例外:'调用未定义的关系[用户]型号[应用\\用户A] .' 我以为只有创建外键框架将“理解”关系。我需要做更多的事情? –
关系是'user' not'users' –
是的,你是对的!现在工作。我知道应该有db表 –