【问题标题】:Equivalent for WHERE clause using Eloquent function等效于使用 Eloquent 函数的 WHERE 子句
【发布时间】:2016-03-28 13:29:10
【问题描述】:

我想将以下 SQL 语句重写为 Eloquent 格式:

    SELECT `id`, `pushbadge`, `pushalert`, `pushsound`
    FROM `devices`
    WHERE `id` IN (1, 2, 3)
        AND `status`='active'"

我的想法是

public function getDevicesWithIDs($ids) {

    $conditions = array();
    foreach($ids as $id) {
        $conditions[] = ['id' => $id];
    }
    var_dump($conditions);

    return Device::where($conditions)->get();
}

但这会返回:

SQLSTATE[42S22]: Column not found: 1054 
Unknown column '0' in 'where clause' 
(SQL: select * from `devices` where (`0` = 1))

【问题讨论】:

    标签: sql laravel eloquent


    【解决方案1】:

    如果$ids 是一个数组

    您可以通过以下方式获得结果

    Device::whereIn('id', $ids)->where('status', 'active')->get(['id', 'pushbadge', 'pushalert', 'pushsound']);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 2019-02-09
      • 2015-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多