Rajib Hossen
Rajib Hossen

Reputation: 128

Laravel 5.2 conditional query in many to many relationships

I have some tables.

products(product_id(pk),title)
product_tag(id(pk),tag_id(fk),product_id(fk))
tags(tag_id(pk),tag_name)

I have also others table with products which have Many to Many Relationships. I establish many to many relationship in Product Model like this.

 public function productTags()
{
    return $this->belongsToMany("App\Model\TagModel","product_tags","product_id","tag_id");
}

What I want is to search by keywords. Say I have some keywords like

['shirts','pant']

keywords array could be contain single item or many items.

I want this keywords to be match with tag_name and retrieve those products who have associated with tag_id via the product_tags table as well as all such products who have titles like this keywords.

Example: Product table

product_id    title
  1            half sleeve shirt
  2            full sleeve shirt
  3            pants
  4            women jeans

product_tag table

  product_id       tag_id
      1               1
      2               1
      3               2
      4               3

tags table

     tag_id         tag_name
       1               mens
       2               pant
       3               women

Now if my search keywords array be like

['shirt','pant']

Result should return the first three product from products table as they match. First two product directly match with keywords and third product match with tag_id.

I also have other table who have many to many relationships with products table.

Upvotes: 1

Views: 796

Answers (2)

Shuvo
Shuvo

Reputation: 113

If you use an external array for tags then you might use this code snippet.

$tag = ['shirts','pant'];
Product::where(function($query) use($tag){
           $query-> whereHas('tags',function($query) use($tag){
               $query->whereIn('name',$tag);
           });
       })
        ->orWhere(function($query) use($tag){
            for($i=0;$i<count($tag);$i++){
                $query->orWhere('name','like','%'.$tag[$i].'%');
            }
        })
    ->get();

Upvotes: 3

Ionut Neculcea
Ionut Neculcea

Reputation: 41

In your SearchController try something like this:

$searchString = Input::get('search');
$results = [];

//search after product name
$products = Product::whereRaw('title LIKE ?', ["%$searchString%"])->get();

//insert each product in result array
foreach($products as $product) {
    $results[] = $product; 
}

//search after tag
$tags = Tag::whereRaw('tag_name LIKE ?', ["%$searchString%"])->get();

//insert each tag in results array
foreach($tags as $tag) {
    foreach($tag->products as $product) {
        //check if product exists in results array
        if (!in_array($product, $results)) {
            $results[] = $product;
        }
    }
}

return $results;

Upvotes: 0

Related Questions