Eloquent Join,多个查询,更改AND到OR

时间:2017-07-18 09:31:46

标签: mysql laravel eloquent

我有以下Eloquent查询:

    CustomerStore::restrictBasedOnSession()
        ->joinCustomerWhere([
            ["first_name", "like", "%$query%"],
            ["last_name", "like", "%$query%"],
            ["phone", "like", "%$query%"]
        ])
        ->joinAddressWhere([
            ["postcode", "like", "%$query%"]
        ])
        ->get([
            'customers.id as id',
            'customers.first_name as firstname',
            'customers.last_name as lastname',
            'customers.phone as phone',
        ]);

使用以下范围

public function scopeJoinCustomerWhere($query, $array)
{
    $query->leftJoin('customers', 'customers.id', '=', 'customer_store.customer_id');

    foreach ($array as $clause) {
        $query->orWhere('customers.' . $clause[0], $clause[1], $clause[2]);
    }

    return $query;
}

public function scopeJoinAddressWhere($query, $array)
{
    $query->leftJoin('customer_addresses', 'customer_addresses.customer_id', '=', 'customer_store.customer_id');

    foreach ($array as $clause) {
        $query->orWhere('customer_addresses.' . $clause[0], $clause[1], $clause[2]);
    }

    return $query;
}


public function scopeRestrictBasedOnSession($query)
{
    return $query->where('store_id', '=', config('app.config.id'));
}

我的问题是,当我转出我对上述Eloquent查询的查询时,我的SQL是

选择customersididcustomersfirst_namefirstnamecustomers。{ {1}}为last_namelastnamecustomersphone

来自phone

    在customer_store上左加入customerscustomers = idcustomer_store     在customer_id上左加入customer_addressescustomer_addresses = customer_idcustomer_store

其中     customer_id = 1和     (store_idcustomers喜欢'%e%'或first_namecustomers喜欢'%e%'或{ {1}}。last_name喜欢'%e%')和(customersphone喜欢'%e%')和     customer_addressespostcode为空

我想改变

其中     customer_store = 1和     (deleted_atstore_id喜欢'%e%'或customersfirst_name喜欢'%e%'或{ {1}}。customers喜欢'%e%')和(last_namecustomers喜欢'%e%')和     phonecustomer_addresses为空

其中     postcode = 1和     (customer_storedeleted_at喜欢'%e%'或store_idcustomers喜欢'%e%'或{ {1}}。first_name喜欢'%e%')或(customerslast_name喜欢'%e%')或     customersphone为空

具体来说,当我在多个表格中执行某个操作时,我不希望表格之间的条件为customer_addresses,我需要它为postcode

如果有人有任何建议我会很感激< 3

1 个答案:

答案 0 :(得分:0)

解决方案是将所有where子句放在相同的范围内,而不是创建多个范围方法。

Eloquent查询将在每个范围方法中对子句进行分组。因此,每个范围方法都是不同的,并且在'AND'中有Eloquent附加条款。

这样的事情:

public function scopeJoinRelationWhere($query, $array)
{
    $query->leftJoin('customer_addresses', 'customer_addresses.customer_id', '=', 'customer_store.customer_id');

    $query->leftJoin('customers', 'customer.id', '=', 'customer_store.customer_id');

    foreach ($array['addresses'] as $clause) {
        $query->orWhere('customer_addresses.' . $clause[0], $clause[1], $clause[2]);
    }

    foreach ($array['customers'] as $clause) {
        $query->orWhere('customers.' . $clause[0], $clause[1], $clause[2]);
    }

    return $query;
}