Answer the question
In order to leave comments, you need to log in
Why doesn't belongsTo() method work in Laravel model?
Given:
1. migration to book users table
Schema::create('books_users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string("email");
});
Schema::create('books', function (Blueprint $table) {
$table->increments("id");
$table->integer("book_user_id")->nullable()->unsigned();
$table->string("author");
$table->string("genre");
$table->smallInteger("year")->unsigned();
$table->string("title");
$table->foreign('book_user_id')->references('id')->on('books_users');
});
namespace App\Models\FrontEnd\Users;
use Illuminate\Database\Eloquent\Model;
class BookUser extends Model
{
protected $table = 'books_users';
protected $fillable = ['first_name', 'last_name'];
public $timestamps = false;
public function books(){
return $this->hasMany('\App\Models\FrontEnd\Books\Book');
}
}
class Book extends Model
{
protected $table = 'books';
protected $fillable = [
'author',
'genre',
'year',
'title',
'book_user_id'
];
public $timestamps = false;
public function owner(){
/*
Вопрос:
Почему тут мне приходится явно указывать колонку?
В случае с моделью BookUser мне не приходилось это делать.
В чем тут разница?
*/
return $this->belongsTo('\App\Models\FrontEnd\Users\BookUser");
}
}
$x = new \App\Models\FrontEnd\Users\BookUser();
$res = $x->first();
dd($res->books->toArray());
$y = new \App\Models\FrontEnd\Books\Book();
$res = $y->first();
dd($res->owner->toArray());
return $this->belongsTo('\App\Models\FrontEnd\Users\BookUser','id');
Answer the question
In order to leave comments, you need to log in
The column must be specified explicitly in both cases.
The fact that it works with an 'id' field is just a coincidence (because it looks like the id's just matched) and will lead to errors later on.
In both cases, you need to explicitly specify the book_user_id field, then everything will work as it should.
And you need to specify because laravel in this case cannot correctly display the name of the connection from the table name.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question