【发布时间】:2014-12-18 10:03:27
【问题描述】:
是否可以使用 eloquent 排除特定行?
我想在查询 #2 的查询 #1 中使用帖子 ID 数组排除行。
【问题讨论】:
-
澄清一下,我可以用这样的一个 id 做到这一点:Post::where('id', '', '25');
-
但是无法弄清楚使用 id 数组执行此操作的语法或方法...
是否可以使用 eloquent 排除特定行?
我想在查询 #2 的查询 #1 中使用帖子 ID 数组排除行。
【问题讨论】:
你可以使用whereNotIn:
Post::whereNotIn('id', array(1, 7, 21))->get();
您可以查看Laravel Query Builder Documentation 以更好地了解它的功能。
【讨论】:
您也可以使用except 排除特定行,如下所示:
Post::all()->except([1,2,4]);
【讨论】:
我在 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
【讨论】: