我有以下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是
选择customers
。id
为id
,customers
。first_name
为firstname
,customers
。{ {1}}为last_name
,lastname
。customers
为phone
phone
的
在customer_store
上左加入customers
。customers
= id
。customer_store
在customer_id
上左加入customer_addresses
。customer_addresses
= customer_id
。customer_store
其中
customer_id
= 1和
(store_id
。customers
喜欢'%e%'或first_name
。customers
喜欢'%e%'或{ {1}}。last_name
喜欢'%e%')和(customers
。phone
喜欢'%e%')和
customer_addresses
。postcode
为空
我想改变
其中
customer_store
= 1和
(deleted_at
。store_id
喜欢'%e%'或customers
。first_name
喜欢'%e%'或{ {1}}。customers
喜欢'%e%')和(last_name
。customers
喜欢'%e%')和
phone
。customer_addresses
为空
到
其中
postcode
= 1和
(customer_store
。deleted_at
喜欢'%e%'或store_id
。customers
喜欢'%e%'或{ {1}}。first_name
喜欢'%e%')或(customers
。last_name
喜欢'%e%')或
customers
。phone
为空
具体来说,当我在多个表格中执行某个操作时,我不希望表格之间的条件为customer_addresses
,我需要它为postcode
。
如果有人有任何建议我会很感激< 3
答案 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;
}