【问题标题】:How to add condition if in laravel query? (laravel 5.3)如果在 laravel 查询中如何添加条件? (laravel 5.3)
【发布时间】:2017-05-30 06:09:03
【问题描述】:

我在 UserRepository.php 中的函数是这样的:

public function displayList($year, $subaccountcode = NULL)
{
    $query = Self::orderBy('programcode')
                 ->orderBy('accountcode')
                 ->findWhere(['year' => $year])
            if(isset($subaccountcode))
                 ->findWhere(['subaccountcode' => $subaccountcode]);
            else
                ;
    return $query;
}

我添加了一个条件来检查 subaccountcode 是否存在。我试图喜欢它,但存在错误:

 2/2 ReflectionException in Container.php line 809: Class App\Repositories\UserRepository does not exist 

我该如何解决这个错误?

更新

我使用第三方包。我从这里得到:https://github.com/andersao/l5-repository

【问题讨论】:

    标签: php laravel repository laravel-5.3 laravel-query-builder


    【解决方案1】:

    这取决于findWhere() 做了什么。如果它类似于find() 并且它返回一个对象,但不是查询生成器的实例,那么执行以下操作:

    $query = Self::orderBy('programcode')->orderBy('accountcode')->findWhere(['year' => $year]);
    
    if (isset($subaccountcode)) {
        $query->findWhere(['subaccountcode' => $subaccountcode]);
    }
    
    return $query;
    

    【讨论】:

    • $Subaccountcode 存在与否,->findWhere (['year' => $ year]) 必须保持运行
    • 存在错误:1/1 BadMethodCallException in Macroable.php line 74: Method findWhere does not exist.
    • @mosestoh 这个方法在 Laravel 中不存在,我以为它的方法是你定义的。如果您确实定义了它,请说明您是如何做到的。如果没有,请在末尾使用where() 而不是findWhere()return $query->get();
    • 如果查询是这样的:public function displayList($year, $subaccountcode = NULL) { $query = Self::orderBy('programcode') ->orderBy('accountcode') ->findWhere(['year' => $year]); return $query; },它可以工作。但是当我添加条件时,它不起作用
    • @mosestoh 当您使用第三方软件包时,您应该在问题中说明这一点。对不起,我不熟悉andersao/l5-repository 包。我建议您编辑您的问题并添加此信息,也许其他人可以帮助您。
    猜你喜欢
    • 2017-08-07
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-15
    • 2017-06-24
    • 2022-01-16
    相关资源
    最近更新 更多