【问题标题】:How can I add a subquery to a query in Laravel app?如何在 Laravel 应用程序中向查询添加子查询?
【发布时间】:2023-02-21 02:32:00
【问题描述】:

我有用户和客户表。

我的每个用户都有一组预定义的查询。例如basic 用户,只能看到类型为newpotential 的客户。

我如何编写一个查询,让用户选择只查看 potential 客户端,或者只查看具有特定名称的客户端?

我现在的做法很简单

$defaultQuery = [['type', 'new'],['type', 'potential']];
$customQuery = ['type', 'new']; // I would pass this, can be null

$customers = Customer::where($defaultQuery[0][0], $defaultQuery[0][1])->orWhere($defaultQuery[1][0], $defaultQuery[1][1])->get();

$customersToReturn = [];

if ($customQuery) {
    foreach($customers as $customer) {
        if ($customer[$customQuery[0]] == $customQuery[1]) {
            $customerToReturn[] = $customer;
        }
    }
} else {
    $customersToReturn = $customers;
}
return $customersToReturn;

我知道有一个 filter() 函数,但我想用子查询进行一个查询。我怎样才能做到这一点?

【问题讨论】:

标签: mysql laravel


【解决方案1】:

您可以将这些查询的责任放在模型和关系本身上

//User.php

public function potentialCustomer(): HasMany
{
    return $this->hasMany(Customer::class)->where('type', '=', 'potential');
}

public function newCustomer(): HasMany
{
    return $this->hasMany(Customer::class)->where('type', '=', 'new');
}

有了这个,你只控制控制器中的调用。像这样:

//controller
$customers = $user->isBasic() ? $user->newCustomer : $user->potentialCustomer;

【讨论】:

    猜你喜欢
    • 2015-02-21
    • 2021-02-03
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    相关资源
    最近更新 更多