【问题标题】:Laravel - Using Where Clause with If Statement and ParameterLaravel - 将 Where 子句与 If 语句和参数一起使用
【发布时间】:2019-06-04 00:32:22
【问题描述】:

我有一个 Laravel 查询,其中包含 where 子句语句和一个参数。来自源的 $plan 是字符串,其值为:

每日、每周、每月、钱包

但是 $plan 在目标用户表 ($users) 中的值是: 1,2,3,4

参数来源:

        @foreach($billings as $key => $billing)
            <tr>
                <td>{{ ++$key }}</td>
                <td><a class="btn btn-info" href="{{ route('revenueDetail',$billing->plan) }}">{{ $billing->plan }}</a></td>
                <td>{{ $billing->total_plans }}</td>
                <td>{{ $billing->total_amount }}</td>
            </tr>
            
        @endforeach
            <tr>
            <td colspan="8">
                {{ $billings->links() }}
            </td>
            </tr> 

控制器:查询

    public function revenueDetail($plan = null)
    {
    $revenuedetails = DB::table("users")
                     ->select(
                       "users.username", 
                       DB::raw("DATE(users.created_at) as subscription_date")
                     )        
                     ->where('users.plan', $plan)
                     ->get();            
    }

我想要实现的是,在revenueDetail()函数的where子句中,如果:

$plan = Daily 然后 users.plan = 1

$plan = Weekly 然后 users.plan = 2

$plan = Monthly 然后 users.plan = 3

$plan = 钱包然后 users.plan = 4

我如何做到这一点?

【问题讨论】:

    标签: laravel


    【解决方案1】:

    根据最后几句话,我假设您需要映射 Daily 字符串 which == 1

    protected static $type = [
        'Daily' => 1,
        'Weekly' => 2,
        'Montly' => 3,
    ]
    

    然后

    public function revenueDetail($plan = null)
    {
        $revenuedetails = DB::table("users")
            ->select("users.username", DB::raw("DATE(users.created_at) as subscription_date"))
            ->where('users.plan', self::$type[$plan] ?? null) // ?? will escape exception if $plan is null
            ->get();          
    }
    

    【讨论】:

    • 我应该把 protected static $type 放在项目的什么地方。模型控制器
    【解决方案2】:

    从视图用户应该发送 id 而不是 value。但是,如果您想发送价值,您应该向计划表询问您发送的价值 id。我建议将计划存储在缓存中。另一个解决方案是像您的计划一样使用 Constans 上课(如果您将来不想扩展它)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-16
      • 2016-02-02
      • 1970-01-01
      • 2011-06-09
      • 1970-01-01
      • 1970-01-01
      • 2016-05-06
      • 2013-03-02
      相关资源
      最近更新 更多