dqnrk44682 2016-01-25 18:29
浏览 29
已采纳

具有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)?

  • 写回答

2条回答 默认 最新

  • dsx58940 2016-01-25 18:39
    关注

    You can use:

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

    This will get both coconut and apples..

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题