【问题标题】:How to get an array result set from Laravel where condition如何从 Laravel where 条件中获取数组结果集
【发布时间】:2017-03-17 04:37:15
【问题描述】:

我正在尝试从 laravel eloquent 查询中获取结果集,借此我将列与数组中的值列表进行匹配。

$authenticated_operation_ids = AccessControl::where('user_id', '=', $user_id)
    ->where('entity_type_id', '=', $operation_entity_id)
    ->pluck('entity_access_id')->toArray();
$authenticated_operations = Operation::whereIn('id', $authenticated_operation_ids);

return view('page.index')->withOperations($authenticated_operations);

【问题讨论】:

  • 您在查询结束时忘记了->get()
  • 在 mongodb 中,本地 id 被创建为 _id 属性。如果你不是故意的,你应该把 id 改成 _id。

标签: php arrays laravel where-in


【解决方案1】:

你可以试试:

$authenticated_operation_ids = AccessControl::where('user_id', '=', $user_id)->where('entity_type_id', '=', $operation_entity_id)->pluck('entity_access_id')->toArray();
$authenticated_operations = Operation::whereIn('id', $authenticated_operation_ids)->get();
return view('page.index')->withOperations($authenticated_operations);

在查询末尾添加get()

【讨论】:

    【解决方案2】:

    1) pluck 从单行返回单个值。您希望lists 从多行中获取单列。 toArray 可能不需要,因为它返回一个值数组

    $authenticated_operation_ids = AccessControl::where('user_id', '=', $user_id)
        ->where('entity_type_id', '=', $operation_entity_id)
        ->lists('entity_access_id');
    

    2) 您忘记实际检索第二行中的行:

    $authenticated_operations = Operation::whereIn('id', $authenticated_operation_ids)
        ->get();
    

    【讨论】:

    • 在 Laravel 5.2 中,集合、查询构建器和 Eloquent 查询构建器对象上的 lists 方法已重命名为 pluckDocs
    • 啊哈,谢谢!那么,这使得#1 没有实际意义。至少,如果他们使用的是 5.2。没有提到任何版本。
    【解决方案3】:

    您必须在结果集上调用 get() 函数才能获得结果。修改后的代码会是这样的

    $authenticated_operation_ids = AccessControl::where('user_id', '=', $user_id)->where('entity_type_id', '=', $operation_entity_id)->get()->pluck('entity_access_id');
    $authenticated_operations = Operation::whereIn('id', $authenticated_operation_ids)->get();
    return view('page.index')->withOperations($authenticated_operations);
    

    或者你可以使用游标来处理它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-19
      • 1970-01-01
      • 2020-08-21
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 2021-09-23
      • 2022-10-06
      相关资源
      最近更新 更多