skip to Main Content

This is a little complex for me,so I decided to get some help.

Taxonomy has :

public function products()
    {
        return $this->belongsToMany(
            Product::class,
            'term_relationships',
            'term_taxonomy_id',
            'object_id'
        );
    }

And Product has :

public function taxonomies()
    {
        return $this->belongsToMany(
            Taxonomy::class,
            'term_relationships',
            'object_id',
            'term_taxonomy_id'
        );
    }

This will select all products with all its taxonomies where taxonomy starts with pa_.

CorcelWooCommerceModelProductCategory::find(401)->products()->with(['taxonomies'=> function ($query) {
        $query->where('taxonomy', 'like', "pa_%");
    }])->get(['ID'])->makeHidden(['pivot']);

All I want is to select only taxonomies which all have the same taxonomy column value.
like they all have : taxonomy -> pa_shirt_size and taxonomy -> pa_shirt_color

Here’s the sql output of eloquent :

select * from `wp_posts` inner join `wp_term_relationships` on `wp_posts`.`ID` = `wp_term_relationships`.`object_id`
where `post_type` = 'product' and `wp_term_relationships`.`term_taxonomy_id` = 401 and exists (select * from
    `wp_term_taxonomy` inner join `wp_term_relationships` on `wp_term_taxonomy`.`term_taxonomy_id` =
                                                             `wp_term_relationships`.`term_taxonomy_id` where `wp_posts`.`ID` = `wp_term_relationships`.`object_id` and `taxonomy`
    like 'pa_%')

So I think using something like :

group by `taxonomy` having count(*) = count(wp.posts.ID)

I can get the number of posts and if that is equal to taxonomy count it means we’re good.
But how to access wp.posts.ID from the subquery in with function I couldn’t find a way yet.

2

Answers


  1. I suggest you get the products’ count, then get all the taxonomies that have all the products count:

     $Products_count = Product::count();
      $sharedTaxomies  = Taxonomy::has('products', '=', $Products_count)->get();
    

    note: I suppoe the relation in Taxonomy called products not posts.

    Login or Signup to reply.
  2. first: i think you mean products() instead posts() ?

    public function products()
        {
            return $this->belongsToMany(
                Product::class,
                'term_relationships',
                'term_taxonomy_id',
                'object_id'
            );
        }
    

    Secound: if you have access to products like:

    $products = Product::all();
    

    you can after iterate the $products and you have access to the taxonomies like:

    print_r( $products[0]->taxonomies );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search