New to Laravel. I have the following tables.
products (
id
)
attributes (
id,
name
)
attribute_values(
id,
attribute_id,
value
)
products_attributes (
product_id,
attribute_value_id
)
I can able to get the product details along with its categories attribute name and value with everything.(it has translations also) Now need to perform the search operation.
(variations is attribute_values)
$products = Product::whereHas('variations', function ($query) use($search_txt) {
$query->where('value','like', $search_txt);
})->get();
$product= product::whereTranslationLike('name', '%'.$search_txt.'%')
->orwhereTranslationLike('description', '%'.$search_txt.'%')
->get();
written the query separately, Don't know how to make it work together.
Can someone help me out with an example?
CodePudding user response:
You may want to group the translation set of conditions.
$products = Product::whereHas('variations', fn ($q) => $q->where('value', 'like', $search_txt))
->orWhere(fn ($q) => $q->whereTranslationLike('name', '%'. $search_txt .'%')
->orWhereTranslationLike('description', '%'. $search_txt .'%'))
->get();
CodePudding user response:
As far as I understand, You can combine both the queries
$product= product::whereTranslationLike('name', '%'.$search_txt.'%')
->orwhereTranslationLike('description', '%'.$search_txt.'%')
->whereHas('variations', function ($query) use($search_txt) {
$query->where('value','like', $search_txt);
})->get();
Please let me know, if it doesn't work
CodePudding user response:
If I understand you correctly, you want to find the value if any of the where statements succeed. The trick is to use the OR in all appending where statements like so:
$products = Product
::whereHas('variations', function ($query) use($search_txt) {
$query->where('value','like', $search_txt);
})
->orWhereTranslationLike('name', '%'.$search_txt.'%')
->orwhereTranslationLike('description', '%'.$search_txt.'%')
->get();
This way you will find products matching a variation value or name or description like $search_text
CodePudding user response:
Now its working I changed like below.
$product = Product::with('variations')->whereHas('variations', function ($query) use($search_txt) {
$query->where('value','like', $search_txt);
})->orwhereTranslationLike('name', '%'.$search_txt.'%')
->orwhereTranslationLike('description', '%'.$search_txt.'%')->get();
