Laravel – 仅从 whereExists 中选择值

huangapple go评论55阅读模式
英文:

Laravel - select only value from whereExists

问题

我在Laravel中有以下查询:

User::whereIn('id', $ids)
    ->withExists(['read' => function($q) use($post) {
        return $q->where('post_id', $post->id);
    }])
    ->select(['id', 'user_name', 'read_exists'])
    ->get();

我想只选择'user_name'和是否存在'read_exist'的信息。但是我遇到了"unknown column read_exist"的错误。

那么我如何只选择这三个值,而不是所有用户列?

英文:

I have following query in laravel:

User::whereIn('id', $ids)
        ->withExists(['read' => function($q) use($post) {
                return $q->where('post_id',  $post->id);
            }]
        )->select(['id', 'user_name', 'read_exists'])->get();

And I would like to select only 'user_name' and information if has any 'read_exist'.
But I have error "unknown column read_exist".

So How can I select only this three values, not all user columns?

Thank you.

答案1

得分: 1

select方法放在withExists之前:

User::whereIn('id', $ids)
    ->select(['id', 'user_name', 'read_exists'])
    ->withExists(['read' => function($q) use($post) {
        return $q->where('post_id',  $post->id);
    }])
    ->get();

文档中有说明。

英文:

Put the select method before withExist

User::whereIn('id', $ids)
->select(['id', 'user_name', 'read_exists'])
->withExists(['read' => function($q) use($post) {
        return $q->where('post_id',  $post->id);
    }]
)->get();

It's stated in the docs

huangapple
  • 本文由 发表于 2023年2月16日 13:57:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75468364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定