admin管理员组文章数量:1392007
I need optimize this query, I have this instruction
$tickets = BITicket::query();
$tickets = $tickets->whereIn("Status_Code", $status);
...
$tickets = $tickets->with("customer")->get();
after I get the records I use a for to check a condition with to fields on the same table
foreach ($tickets as $key => $value) {
if ($value->Tipo_de_Pago_Ticket == "some number") {
if ($value->Subject != "Some Value") {
$tickets->fet($key);
}
}
}
so, I need change the for
for another option inside the query, I tried with when
funcion, subqueries but doesn't work.
somebody know how make this istruccion $tickets->fet($key);
inside the query
I need optimize this query, I have this instruction
$tickets = BITicket::query();
$tickets = $tickets->whereIn("Status_Code", $status);
...
$tickets = $tickets->with("customer")->get();
after I get the records I use a for to check a condition with to fields on the same table
foreach ($tickets as $key => $value) {
if ($value->Tipo_de_Pago_Ticket == "some number") {
if ($value->Subject != "Some Value") {
$tickets->fet($key);
}
}
}
so, I need change the for
for another option inside the query, I tried with when
funcion, subqueries but doesn't work.
somebody know how make this istruccion $tickets->fet($key);
inside the query
1 Answer
Reset to default 0Try something like this:
$tickets = BITicket::query()
->whereIn("Status_Code", $status)
->where(function ($query) {
$query->where('Tipo_de_Pago_Ticket', '!=', 'some number')
->orWhere(function ($q) {
$q->where('Tipo_de_Pago_Ticket', 'some number')
->where('Subject', 'Some Value');
});
})
->with('customer')
->get();
Explanations:
MySQL doesn't have IF(well, it does, but it a different kind), we can use where and orWhere instead. And grouping with ->where(function ($query)
or ->orWhere(function ($q)
act as brakets. Your SQL will look like this
SELECT * FROM bit_tickets
WHERE Status_Code IN ('some status', 'other status')
AND (
Tipo_de_Pago_Ticket != 'some number'
OR (Tipo_de_Pago_Ticket = 'some number' AND Subject = 'Some Value')
)
See, some wheres are grouped with brackets and whole grouped condition must be true. Laravel's default ->where()
acts as AND
.
本文标签: laravelIf statements in eloquent QueriesStack Overflow
版权声明:本文标题:laravel - If statements in eloquent Queries - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744732550a2622134.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
$tickets = $tickets->where('Tipo_de_Pago_Ticket', 'some number')->where('Subject', '!=', 'Some Value')->whereIn('Status_Code', $status);
? – apokryfos Commented Mar 12 at 20:26$tickets
if$ticket->Tipo_de_Pago_Ticket
is "some number" and$ticket->Subject
is "Some Value" --these two conditions met? Please clarify. – Subha Commented Mar 13 at 5:22