【问题标题】:Create SQL query with more than one where clause使用多个 where 子句创建 SQL 查询
【发布时间】:2013-05-13 18:18:32
【问题描述】:

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

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

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

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    简单,换个where

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

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

    如果您只想使用 Query Builder(Fluent),请将 Model:: 替换为 DB::table('table1')->

    注意

    • = 在这里是可选的。在这里您可以使用其他运算符。

    更新

    从 Laravel 4.2 你也可以使用数组:

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

    【讨论】:

    • 关于查询的另一个问题,我想在 Eloquent 中执行类似“SELECT r.id, avg(p.puntuacio) FROM receptes AS r, puntuacio_receptes_usuaris AS p WHERE r.id = p. recepta_id GROUP BY r.id" 但我不知道该怎么做
    • 你能把这个作为一个新问题发布,我会在空闲时间回答它吗?
    【解决方案2】:

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

    雄辩的对象:

    class User extends Eloquent {
    
        protected $table = 'table1';
    
        ...
    }
    

    ORM 查询:

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

    【讨论】:

    • 不完全正确,您可以使用 DB::table('table1') 代替 Eloquent 模型。此外,您只需要 whereorWhere 进行链接(而不是 andWhere)。
    • 没错,你可以用 fluent 做到这一点,但他要求的是 Eloquent。修复了,谢谢指点。
    猜你喜欢
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 2011-12-03
    • 2014-06-20
    • 2019-10-25
    相关资源
    最近更新 更多