Laravel Eloquent 如何在单个 WHERE 子句中使用 && 或 AND。

huangapple go评论60阅读模式
英文:

Laravel Eloquent how to use && or AND inside single WHERE clause

问题

我正在尝试在Laravel中使用Eloquent模型进行查询。

我的原始查询不起作用

Query1::where('Course_ID', '=', $request->FLA)
    ->where('Date', '=', Carbon::today())

我想要将查询合并到单个WHERE条件中,类似于:

Query1::where('Course_ID', '=', $request->FLA && 'Date', '=', Carbon::today())

这种操作是否可行?

英文:

I am trying to make a query using Eloquent Model in Laravel.

My original query does not work

Query1::where('Course_ID', '=', $request->FLA)
->where('Date', '=', Carbon::today())

I would like the query to include both inside of a single WHERE, akin to:

Query1::where('Course_ID', '=', $request->FLA && 'Date', '=', Carbon::today())

Is this possible?

答案1

得分: 1

你可以使用:

Query1::where([
   'Course_ID' => $request->FLA,
   'Date' => Carbon::today()
]);

它会创建以下的SQL查询:

SELECT * FROM tablename WHERE Course_ID = ? AND Date = ?

但是你的方法,使用两个 'where' 会产生相同的输出。

英文:

You can use:

Query1::where([
   'Course_ID' => $request->FLA,
   'Date' => Carbon::today()
]);

It will create the following SQL query:

SELECT * FROM tablename WHERE Course_ID = ? AND Date = ?

But your approach, using two 'where's will have the same output

答案2

得分: 0

你所编写的查询方式,使用 ->where()->where() 将生成以下查询:

SELECT * FROM query_1 WHERE Course_ID = ? AND Date = ?

如果你希望你的 WHERE 子句被"范围限定",你可以使用以下语法:

Query1::where(function ($subQuery) use ($request) {
  return $subQuery->where('Course_ID', '=', $request->FLA)
  ->where('Date', '=', Carbon::today());
})->get();

这将生成以下查询:

SELECT * FROM query_1 WHERE (Course_ID = ? AND Date = ?)

请注意,Course_ID = ? AND Date = ? 周围有 ()

这在你想要添加需要分组的条件时非常有用,例如,如果你要添加另一个可能与现有条件冲突的 WHERE 子句。

英文:

The way you have your query written, using ->where()->where() will generate the following query:

SELECT * FROM query_1 WHERE Course_ID = ? AND Date = ?

If you want your WHERE clause to be "scoped", you can use this syntax:

Query1::where(function ($subQuery) use ($request) {
  return $subQuery->where('Course_ID', '=', $request->FLA)
  ->where('Date', '=', Carbon::today());
})->get();

This will generate the query:

SELECT * FROM query_1 WHERE (Course_ID = ? AND Date = ?)

Notice the () around Course_ID = ? AND Date = ?

This is useful when you want to add conditions that need to be grouped, i.e. if you were adding another WHERE that could conflict with the existing one(s).

答案3

得分: 0

如果您的"Date"列是日期类型,请尝试以下方式:

Query1::where('Course_ID', '=', $request->FLA)->where('Date', '=', Carbon::now()->toDateTimeString());
英文:

If your Date column is type of date, please try like that

Query1::where('Course_ID', '=', $request->FLA)->where('Date', '=', Carbon::now()->toDateTimeString());

huangapple
  • 本文由 发表于 2023年8月4日 01:13:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830279.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定