laravel 使用多个 where 子句创建 SQL 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16528553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:46:36  来源:igfitidea点击:

Create SQL query with more than one where clause

phplaravellaravel-4

提问by Ruben

I'm trying to do a query with 2 whereclauses like:

我正在尝试使用 2 个where子句进行查询,例如:

select * from table1 where `name` = 'paul' AND `id` = 1

in Laravel with Eloquent, but I don't know the correct syntax.

在 Laravel 中使用 Eloquent,但我不知道正确的语法。

回答by Muhammad Usman

Simple, use another where

简单,使用另一个 where

Model::where('name', '=', 'paul')->where('id', '=', 1);

Then you may use get()or first()to fetch the row(s).

然后您可以使用get()first()来获取行。

If you want to use just Query Builder(Fluent) then replace Model::with DB::table('table1')->.

如果您只想使用 Query Builder(Fluent) 然后替换Model::DB::table('table1')->.

Note

笔记

  • =is optional here. Here you can use other operators.
  • =在这里是可选的。在这里您可以使用其他运算符。

Update

更新

From Laravel 4.2 you can also use array:

从 Laravel 4.2 开始,您还可以使用数组:

Model::where([
               'name' => 'paul', 
               'id' => 1
             ]);

回答by Rok Burgar

You have to have an object that corresponds to table1.

您必须有一个对应于 table1 的对象。

Eloquent object:

雄辩的对象:

class User extends Eloquent {

    protected $table = 'table1';

    ...
}

ORM query:

ORM 查询:

$user = User::where('name', 'paul')
              ->where('id', 1)
              ->first();