Home > Mobile >  Laravel Mongodb Getting Data from the same collection but has different type
Laravel Mongodb Getting Data from the same collection but has different type

Time:07-08

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

CodePudding user response:

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'
  • Related