首先,这是我的第一个Laravel项目,这只是我拼凑起来学习的东西,所以请对我轻松一点。
假设我正在创建一个代表库的应用程序。每本书都有一些关于它的信息( BookInfo ),每一本BookInfo都包含一个(参考) BookType,表示它是“虚构的”还是“非虚构的”。
因此,如果我的BookInfo模式看起来有点像:
//...
$table->unsignedBigInteger('book_id');
$table->unsignedBigInteger('book_type_id');
//...
$table->foreign('book_id')->references('id)->on('books');
$table->foreign('book_type_id')->references('id)->on('book_type');我的BookType模式如下所示:
//...
$table->id();
$table->string('name');BookInfo模型上返回BookType的方法是什么?
我已经做到了这一点,并且似乎尝试了无数的备选方案(错误略有不同):
public function type()
{
return BookType::where('book_type_id', $this->book_type_id)->get()->first();
}是的,我确信我试图查找的id存在于book_type表中。我其实只想要->name的BookType,但很明显,我需要先得到BookType .
发布于 2022-08-12 15:13:14
public function type(): BelongsTo
{
return $this->belongsTo(BookType::class, 'book_type_id');
}如果将方法名更改为bookType,则可以将第二个参数省略为belongsTo,因为它将根据方法名自动解析外键,您只需执行以下操作:
public function bookType(): BelongsTo
{
return $this->belongsTo(BookType::class);
}以下是来自Laravel的雄辩的关系参考:https://laravel.com/docs/9.x/eloquent-relationships
发布于 2022-08-12 15:42:15
用于外键的迁移:$table->foreignIdFor(BookType::class, 'book_type_id');
https://stackoverflow.com/questions/73335379
复制相似问题