首页 > 解决方案 > 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;

标签: phplaravelwebweb-applicationsframeworks

解决方案


使用 Eloquent 关系,您可以将它们作为属性访问以访问相关模型或访问方法以查询或执行其他操作。

由于您想要一个画廊模型及其相关的图像模型,您可以访问两者的属性:

$room_gallery = $room->gallery->images;

使用 HasOne,$room->gallery本质上等于$room->gallery()->first()。使用 HasMany,$gallery->images基本上等于$gallery->images()->get().

但是,这可能是HasManyThrough关系派上用场的情况。


推荐阅读