具有where-functions限制的Laravel查询构建器

I am trying to sort by a selection users can make, where the items are stored in "type" table in the database. I am using Laravel 5.2.

Screenshot of the multiple select function (text in danish):

enter image description here

They can for example select (in a multiselect):

  • Apple
  • Banana
  • Coconut
  • Watermelon

If they select only Apple, all Apples should be shown - easy enough. But if they select both Apples and Coconut, both Apples and Coconut should be shown.

$query = User::where('type', '=', 'Apple')->get(); 

gets all the apples.

But if i do:

$query = User::where('type', '=', 'Apple')->where('type', '=', 'Coconut')->get();

Only users who have selected both Apple and Coconut would be shown. It is not possible for the user to select both apples and coconuts in backend, and therefore no users are shown.

How can I build a query, where users who have selected type Apple or Coconut in backend, would be shown by building a query which doesn't limit the output to be only if the user has selected both (which is not possible for the user)?

You can use:

$query = User::where(function($query) {
$query->where('type', '=', 'Apple')
->orWhere('type', '=', 'Coconut');
)}->get();

This will get both coconut and apples..

If you're looking to limit the results to Apples or Coconuts, you should use the correct ->orWhere() statement, instead of another ->where(). By default, chaining ->where() clauses will result in WHERE ... AND ... AND .... Changing your $query to:

$query = User::where('type', '=', 'Apple')->orWhere('type', '=', 'Coconut')->get();

will result in the query WHERE ... OR ..., and limit your results to Apples or Coconuts.