php - Laravel 5.4 SQL 查询嵌套 Where/OrWhere

标签 php mysql laravel eloquent

我有这些表

贷款表 | coop_id |贷款编号 |贷款可用性|

贷款季节表 | coop_id |贷款编号 | loan_season_start | loan_season_end |

我正试图在一个数组中获取每笔贷款的详细信息,无论它们的可用性是Always 还是Seasonal。如果标记为季节性,则它在贷款季节表中有一个数据。

这是我的查询

$loanlist = DB::table('loans')
        ->join('loan_seasons', 'loan_seasons.loan_id', 'loans.loan_id')
        ->where('loans.coop_id', $coop_id)
        ->where(function ($q){ 
            $q->where('loans.loan_availability', "Always")
            ->orWhere(function ($qq){ 
                $qq->where('loans.loan_availability', "Seasonal")  
                ->where('loan_season_start', '>=', Carbon::now()->month)
                ->where('loan_season_end', '<=', Carbon::now()->month)
                ->where('loan_season_status', 1);
            });
        })
        ->where('loans.loan_status', "1")
        ->get()->toArray();

我得到这个输出:

Array(
    [0] => Array(
        [id] => 2
        [coop_id] => 1
        [loan_id] => 3
        [loan_name] => Loan 1
        [loan_desc] => Loan 1 Description
        [loan_maxamount] => 500000
        [loan_availability] => Always
        [loan_status] => 1
        [created_at] => 2017-02-26 17:43:08
        [updated_at] => 2017-02-26 17:43:08
        [loan_season_start] => 2
        [loan_season_end] => 6
        [loan_season_status] => 1
    )
)

我期望的输出是这样的:

Array(
    [0] => Array(
        [id] => 1
        [coop_id] => 1
        [loan_id] => 3
        [loan_name] => Loan 1
        [loan_desc] => Loan 1 Description
        [loan_maxamount] => 500000
        [loan_availability] => Always
        [loan_status] => 1
        [created_at] => 2017-02-26 17:43:08
        [updated_at] => 2017-02-26 17:43:08
        [loan_season_status] => 1
    )
   [1] => Array(
        [id] => 2
        [coop_id] => 1
        [loan_id] => 4
        [loan_name] => Loan 2
        [loan_desc] => Loan 2 Description
        [loan_maxamount] => 200000
        [loan_availability] => Seasonal
        [loan_season_start] => 2
        [loan_season_end] => 6
        [loan_status] => 1
        [created_at] => 2017-02-26 17:43:08
        [updated_at] => 2017-02-26 17:43:08
        [loan_season_status] => 1
    )
)

我已经尝试解决这个问题几个小时了,但我仍然无法正确查询。有人可以帮忙吗?我对嵌套查询很陌生。帮忙?

最佳答案

我现在开始工作了。好像我一直在使简单的查询变得复杂。我为每个条件创建了不同的查询,并将它们合并为一个。谢谢。

关于php - Laravel 5.4 SQL 查询嵌套 Where/OrWhere,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42473533/

相关文章:

java - 从数据库表中提取信息 php

php - Doctrine 多级继承映射

php - WAMP 服务器不允许 php 搜索引擎?

laravel - 包含 Vue.js v-if 和 v-for 指令的 HTML 标签在加载时闪烁

php - 如何用新行替换所有 XHTML/HTML 换行符 (<br>)?

php - while 循环在 PHP 中不能正常工作吗?

MySQL - 连接 a 或 b

mysql - 我们可以通过检查 SQL 和 HQL 中的 if else 条件来设置表名吗?

php - 如何使用 Laravel 5.* 将二进制数据插入 SQL

laravel - 如何为广播身份验证路由定义或传递身份验证防护而不是默认身份验证防护?