【问题标题】:PHP. Filtering data in Eloquent ORMphp。在 Eloquent ORM 中过滤数据
【发布时间】:2013-05-15 08:00:16
【问题描述】:

我正在尝试从使用 Eloquent 的数据库中获取的对象中删除一些元素。

我有一个分配给变量 $words 的对象

$words = Word::all();

当我将 $words 显示为 JSON 时,它看起来像这样:

[
{
"id": "1",
"word": "dog",
"phonetic": "dog",
"mean": "pies",
"assoc": "some example text",
"author_id": "3",
"user_id": "3"
},
{
"id": "2",
"word": "sun",
"phonetic": "sun",
"mean": "słońce",
"assoc": "lorem ipsun dolor sit amet",
"author_id": "3",
"user_id": "2"
}, ...
]

我想要做的是从整个对象中删除那些实体,例如,值“user_id”设置为 2、4 或 5。这个 id 存储在一个数组中。

使用 Eloquent ORM 实现它的最佳方法是什么?使用 Word::where(...) 是不够的,因为据我所知,它只能取一个值。我试图用 foreach 循环来做到这一点,但过去迭代对象 $words 返回时没有更改。

【问题讨论】:

    标签: php orm filtering eloquent


    【解决方案1】:

    使用where_not_in()怎么样? http://laravel.com/docs/database/fluent

    像这样:

    DB::table('users')->where_not_in('id', array(2, 4, 5))->get();
    

    【讨论】:

    • 不幸的是,我使用 Eloquent 和 Slim 框架,而不是整个 Laravel。
    【解决方案2】:

    我没有清楚地理解你的问题,但是如果你想绑定多个 where 语句,你可以使用 where 语句作为闭包并在里面使用你的 foreach 循环。

    这样的事情可能会奏效;

    $result = Word::where(function($query) use ($words) {
        foreach($words $k => $v)
        {
            //Whatever you want to bind into where
            $query->where($v, '=', 1);
        }
    })->delete();
    

    【讨论】:

    • 也许还不够理解。对不起。我不想过滤对象:仅从我传递给客户端的对象中删除实体,而不是从数据库中删除它们。
    • 至少我用过这样的东西:$words = Word::all(); $result = Word::where(function($query) use ($words){ foreach ($words as $key => $value) { foreach ($idArray as $key) { $query->where('id', '!=', $key); } } })->get();谢谢!
    猜你喜欢
    • 2015-04-04
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多