In my scenario, I have the tables of users and teachers, where a teacher has a user, so I have a 1:1
relation.
Migrations:
create_users_table
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 150);
$table->string('username', 20)->unique();
$table->string('email', 100)->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
create_teachers_table
Schema::create('teachers', function (Blueprint $table) {
$table->increments('id');
$table->date('birth');
$table->string('about');
$table->integer('user')->unsigned();
$table->foreign('user')->references('id')->on('users');
$table->timestamps();
});
Models:
User
protected $fillable = [
'username', 'email', 'password', 'name', 'remember_token',
];
protected $hidden = [
'password', 'remember_token'
];
public function teacher() {
return $this->belongsTo(Teacher::class, 'teacher');
}
Teacher
protected $fillable = [
'user', 'birth', 'about',
];
public function user()
{
return $this->hasOne(User::class, 'user');
}
Controller Where do I try to create a teacher:
$f_teacher = $request->only('birth', 'about');
$f_user = $request->except('birth', 'about', '_token');
$teacher = new Teacher($f_teacher);
$teacher->user()->save( new User($f_user) );
$teacher->save();
When you run this page, the following error appears:
QueryException in Connection.php line 770: SQLSTATE [42S22]: Column not found: 1054 Unknown column 'user' in 'field list' (SQL:
insert into users (name, email, username, password, user, updated_at, created_at) values (Nome do professor, [email protected], user-prof, senha-criptografada, ,2017-01-07 00:26:44, 2017-01-07 00:26:44)
)
I know the error is because Laravel is reversing the relation, it is interpreting that the users
table has the FK user
and the% does not have, I tried to invert by putting HasOne in the user model and BelongsTo in the teacher model, but as expected did not work. Why is this relationship being reversed? How to solve?