【问题标题】:Eloquent - Excluding specific rowsEloquent - 排除特定行
【发布时间】:2014-12-18 10:03:27
【问题描述】:

是否可以使用 eloquent 排除特定行?

我想在查询 #2 的查询 #1 中使用帖子 ID 数组排除行。

【问题讨论】:

  • 澄清一下,我可以用这样的一个 id 做到这一点:Post::where('id', '', '25');
  • 但是无法弄清楚使用 id 数组执行此操作的语法或方法...

标签: mysql laravel-4 eloquent


【解决方案1】:

你可以使用whereNotIn:

Post::whereNotIn('id', array(1, 7, 21))->get();

您可以查看Laravel Query Builder Documentation 以更好地了解它的功能。

【讨论】:

  • 这正是我需要的!我不知道我是如何在文档中错过它的...谢谢!
【解决方案2】:

您也可以使用except 排除特定行,如下所示:

Post::all()->except([1,2,4]);

【讨论】:

    【解决方案3】:

    我在 Collection 上使用过这个makeHidden()

    我的例子如下:

    //In Repository
    public function getAdminPermissions(int $user_id): Collection
    {
        return $this->model->where('user_id',$user_id)->get();
    }
    
    //In Service function
    ...
    /** @var UserAdminRepository $userAdminRepository */
    $userAdminRepository = app(UserAdminRepository::class);
    $adminPermissionsCollection = $userAdminRepository->getAdminPermissions($data['user_id']);
    if ($adminPermissionsCollection->isEmpty()) {
        throw new EmptyDatasetException("User with ID {$data['user_id']} does not have any data in corresponding table");
    }
    $adminPermissionsCollection->makeHidden(['user_id','created_at','updated_at']);
    
    

    实际上有很多方法可以解决这个问题,其中一种可能的方法是您使用 Resource 并利用 toArray 函数

    另外一种情况是,如果您明确依赖 Eloquent 模型,您可以在模型类本身上使用 $hidden 属性。 Reference $hidden property

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 2023-04-02
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      相关资源
      最近更新 更多