Search code examples
laraveleloquentpolymorphismlaravel-8laravel-query-builder

laravel oneToMany query return all records by taggable_id and taggable_type


i want to select all user_tag_id where they have the same taggable_type and taggable_id. FYI, im not that good at using query and laravel is still new to me so im still learning.

this is what i've tried so far,

$check = Tag::whereIn('user_tag_id', function ( $query ) {
            $query->select('taggable_id')->from('tags')->groupBy('user_tag_id');
        })->get();
        return $check;

which did return this,

"id" => 1
        "user_tag_id" => 1
        "taggable_type" => "App\Domains\TradeSetup\Models\TradeSetup"
        "taggable_id" => 1
        "type" => null
        "state" => null
        "created_at" => "2022-11-25 01:57:42"
        "updated_at" => "2022-11-25 01:57:42"
        "deleted_at" => null

"id" => 6
        "user_tag_id" => 1
        "taggable_type" => "App\Domains\Trade\Models\Trade"
        "taggable_id" => 1
        "type" => null
        "state" => null
        "created_at" => "2022-11-25 02:31:24"
        "updated_at" => "2022-11-25 02:31:24"
        "deleted_at" => null

this is the model:

//TradeSetup model

    public function userTag()
    {
        return $this->hasMany(UserTag::class);
    }

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

// Tag model

public function taggable()
    {
        return $this->morphTo();
    }

    public function userTag()
    {
        return $this->belongsTo(UserTag::class);
    }

except i don't know how to only return, for example user_tag_id where taggable_type = TradeSetup and taggable_id = 1

basically i suspect the query would look something like this

SELECT USER_TAG_ID
FROM TAGS
WHERE (TAGGABLE_ID = 1) AND
WHERE (TAGGABLE_TYPE = TRADESETUP)

so i suspect the it will only return all the records based on user_tag_id which have taggable_id = 1 and taggable_type = TradeSetup.


Solution

  • So if I understand you correctly you have a user relation for the tags model. So the query should look like this

    Tag::whereHas('user_tag_id', function ($query) {
       $query->where('taggable_id', 1)->where('taggable_type', 'App\Domains\TradeSetup\Models\TradeSetup');
    })->get();
    

    If I misunderstood your model setup lemme know in the comments so I can edit the answer, Cheers!

    EDIT 1# So as I understand you, you only need to return tags where they have the UserTag relationship so you can do that like this

    Tag::whereHas('userTag')->where('taggable_id', 1)->where('taggable_type', 'App\Domains\TradeSetup\Models\TradeSetup')->get()