拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 聚合后的雄辩选择栏位

聚合后的雄辩选择栏位

白鹭 - 2022-03-25 1952 0 0

我有三个模型UserPostCommentUserPost处于一对多关系中, 和 也是User如此Comment就本示例而言,存在Post-Comment关系。

当我运行以下查询时

User::withCount(['posts', 'comments'])->get()

我得到了预期的结果:

[
...
  App\Models\User {#3459
    id: 18,
    username: "Foo",
    created_at: "2021-12-08 11:38:39",
    updated_at: "2021-12-08 11:38:39",
    posts_count: 5,
    comments_count: 15,
  }
...
]

我想从结果模型中洗掉时间戳。我尝试将我想要的栏位阵列作为自变量get(如->get(['username', 'posts_count', 'comments_count']),但结果根本没有改变。

我也尝试用 替换get(...)select(...)->get()但这会产生此错误:

Illuminate\Database\QueryException with message 
'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts_count' in 'field list'  
(SQL: select `username`, `posts_count`, `comments_count` from `users`)'

我认为这是由于聚合函式尚未执行。

所以我想出了这个解决方案

$usersWithCounts = User::withCount(['posts', 'comments'])->get()
    ->map(function ($item, $key) {
         return $item->only(['username', 'posts_count', 'comments_count']); 
      });

但感觉不对:回传的集合不再由 Eloquent 模型组成,只是简单的阵列。

[
...
  [
    username: "Foo",
    posts_count: 5,
    comments_count: 15,
  ]
...
]

正确的处理方式是什么?

uj5u.com热心网友回复:

以下代码可能适合您的需求:

class User extends Model
{
    protected $hidden = ['created_at', 'updated_at'];
}

uj5u.com热心网友回复:

是的,您肯定使用上述方法过滤收集资料。另一种方法是使用集合的忘记(),使用键从集合中洗掉值。

有关更多信息,请参阅以下链接

忘记收集方法

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *