how do I select morphToMany relationship based on the morphable type?

Published 1 week ago by nikocraft

I want to do something like this:

Tag::where('taggable_type', 'App\Models\Core\Media\Image')->get()

Image model has Tags, which are defined like

public function tags()
{
    return $this->morphToMany(Tag::class, 'taggable');
}

And then we have two migrations

    Schema::create('tags', function (Blueprint $table) {
        $table->increments('id');
        $table->string('title');
        $table->string('slug')->unique();
        $table->timestamps();
    });

and

    Schema::create('taggables', function (Blueprint $table) {
        $table->integer('tag_id');
        $table->integer('taggable_id');
        $table->string('taggable_type');
    });

so ofc I cant do this Tag::where('taggable_type', 'App\Models\Core\Media\Image')->get()

since tag model it self does not have taggable_type, but the polymorph pivot table has. How can I query tag table but let it only return stuff where taggable_type is of this 'App\Models\Core\Media\Image'?

Best Answer (As Selected By nikocraft)
Abi

you need to do something like


Tag::has('image')->get()


more info at https://laravel.com/docs/5.6/eloquent-relationships#querying-relationship-existence

Abi
Abi
1 week ago (76,890 XP)

you need to do something like


Tag::has('image')->get()


more info at https://laravel.com/docs/5.6/eloquent-relationships#querying-relationship-existence

nikocraft

you don't post for 10 months and you help me, thank you @Abi appreciated! :)

Please sign in or create an account to participate in this conversation.