简体   繁体   中英

query case with Laravel and Eloquent ORM

Simply , I want to fetch products with certain size from the DB

each product has sizes column : which contains (for example) : "XS,M,L"

I run this statement

return DB::table('products')->where([['sizes', 'LIKE', "%".$size."%"]])->paginate(1);

for example if $size = "L" , it fetches any product with "L" or "XL" or "XXL" - and that's normal with my statement

I ask now about method to fetch only a certain size

I recommend to use store value in separate rows in other table so that it is easy to query.

Although you do it by find_in_set with whereRaw

DB::table('products')
    ->whereRaw("FIND_IN_SET('L',sizes)")
    ->paginate(1);

If you want to fetch the exact size then you can try

return DB::table('products')->where(['sizes',  $size])->paginate(1);

use = instead of Like .

For more use cases here are the different examples.

WHERE sizes LIKE 'L%'   //Finds any values that starts with "L"
WHERE sizes LIKE '%L'   //Finds any values that ends with "L"
WHERE sizes LIKE '%or%' //Finds any values that have "or" in any position
WHERE sizes LIKE '_r%'  //Finds any values that have "r" in the second position
WHERE sizes LIKE 'a_%_%'    //Finds any values that starts with "a" and are at least 3 characters in length
WHERE sizes LIKE 'a%o'  //Finds any values that starts with "a" and ends with "o"

You have also a typo in your code

Change this

return DB::table('products')->where([['sizes', 'LIKE', "%".$size."%"]])->paginate(1);

To this

return DB::table('products')->where('sizes', 'LIKE', "%".$size."%")->paginate(1);

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM