Laravel MongoDB从同一集合中获取数据,但具有不同的类型

发布于 2025-02-13 15:24:12 字数 242 浏览 0 评论 0原文

我正在尝试制作一个VOD和ADUIO流媒体平台,并且使用Laravel 9和MongoDB作为数据库。

我有一个包含所有媒体的集合,这是一个音频或视频,对我来说,它们是一个称为“类型”的属性,它具有'音频'或“视频”的枚举。我有一个称为媒体的模型,可以同时访问Aduio和视频,我想制作一个音频模型,该模型只能访问具有“音频”的媒体。

使用同一集合时有什么方法可以应用过滤器?还是我需要创建另一个集合才能获得这种收获?

提前致谢

I am trying to make a VOD and Aduio Streaming platform and I am using Laravel 9 and Mongodb as a database.

I have one collection that has all the media in it wether it's an audio or a video, what's seperating them for me is an attribute called "type", and it has an enum of 'audio' or 'video'. I have one model called Media which can access both aduio and Video, and I would like to make an Audio Model that can access only the media who has type 'audio'.

Is there any way to apply filter while using the same collection? Or do I need to create another collection to be able to acheive that?

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

森末i 2025-02-20 15:24:12

的,可以使用 eloquent的查询范围功能。

是 已经有一个“媒体”模型,您可以从中访问音频和视频。

现在,您要创建一个“音频”模型,该模型只能访问类型音频的媒体。 IE type ='Audio'

这是您可以做到的。

class Audio extends Model
{
    // All other stuff in model

    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::addGlobalScope('audio', function (Builder $builder) {
            $builder->where('type', 'audio');
        });
    }
}

全局范围使您可以在给定模型的所有查询中添加约束。

在上面的示例中添加范围为App \ Models \ Audio模型后,对Audio :: all()方法的调用将执行以下SQL查询:

select * from `medias` where `type` = 'audio'

Yes, it's possible using the eloquent's query scope feature.

As you mentioned, you already have a "Media" model from which you can access both Audio and Video.

Now you want to create an "Audio" model which will only access the media of type audio. i.e. type = 'audio'

Here is how you can do it.

class Audio extends Model
{
    // All other stuff in model

    /**
     * The "booted" method of the model.
     *
     * @return void
     */
    protected static function booted()
    {
        static::addGlobalScope('audio', function (Builder $builder) {
            $builder->where('type', 'audio');
        });
    }
}

Global scopes allow you to add constraints to all queries for a given model.

After adding the scope in the example above to the App\Models\Audio model, a call to the Audio::all() method will execute the following SQL query:

select * from `medias` where `type` = 'audio'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文