php - Laravel 访问 hasMany 的 hasOne
问题描述
我有房间、画廊和图像。我想将画廊与房间相关联,然后我想使用房间模型访问分配的画廊的图像。我是 Laravel 的新手,我查看了 YouTube 课程和文档,但没有找到解决问题的方法。
房间.php:
class Room extends Model
{
protected $table = 'rooms';
public function gallery()
{
return $this->hasOne('App\Gallery');
}
}
图库.php:
class Gallery extends Model
{
protected $table = 'gallery';
public function images()
{
return $this->hasMany('App\Image');
}
public function room()
{
return this->belongsTo('App\Room');
}
}
房间控制器.php:
$room = Room::findOrFail($id);
$room_gallery = $room->gallery()->images;
return $room_gallery;
解决方案
使用 Eloquent 关系,您可以将它们作为属性访问以访问相关模型或访问方法以查询或执行其他操作。
由于您想要一个画廊模型及其相关的图像模型,您可以访问两者的属性:
$room_gallery = $room->gallery->images;
使用 HasOne,$room->gallery
本质上等于$room->gallery()->first()
。使用 HasMany,$gallery->images
基本上等于$gallery->images()->get()
.
但是,这可能是HasManyThrough关系派上用场的情况。
推荐阅读
- c# - 有没有办法通过另一个对象/小部件检测 MouseOver?
- python - 尝试运行已编译的 Cython 代码时出现“python39.dll not found”错误
- database-design - 您将如何设置数据库来处理博客站点的评论?
- css - 删除导航栏页面中的左右填充
- r - 基于R中的其他两列减去一列中的值
- c# - 选择 DataGridRow 选定的列 - WPF c#
- ruby - 生成字符串的所有可能大小写
- postgresql - Zeppelin 抛出 java.sql.SQLException:在 AWS 上运行演示 pyspark 脚本时没有合适的驱动程序
- angular-dart - 使用最新的 dart SDK 运行 AngularDart(空安全)
- glsl - GLSL/Shadertoy 生长六边形网格