Laravel Eloquent,在 whereHas 中对我的查询应用选择操作。

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

Laravel Eloquent, apply select on my queries in whereHas

问题

以下是您的代码部分的中文翻译:

$prestations = Prestation::with('service', 'facility', 'conciergeries.network')
    ->whereHas('service', function ($query) use ($searchService) {
        $query->addSelect('id', 'name')->where('name', 'regexp', "/$searchService/i");
    })
    ->whereHas('facility', function ($query) use ($searchPartenaire) {
        $query->addSelect('id', 'name')->where('name', 'regexp', "/$searchPartenaire/i");
    })
    ->whereHas('conciergeries.network', function ($query) use ($searchFiliale) {
        $query->addSelect('id', 'name')->where('name', 'regexp', "/$searchFiliale/i");
    })
    ->where('name', 'regexp', "/$search/i")
    ->orderBy($orderBy, $orderDirection)
    ->paginate(50);

请注意,我已经将代码部分翻译成中文,只包括代码内容,没有其他信息。如果您需要任何其他帮助,请告诉我。

英文:

Here my code :

$prestations = Prestation::with('service','facility','conciergeries.network')
            ->whereHas('service', function ($query) use ($searchService) {
                $query->addSelect('id','name')->where('name', 'regexp', "/$searchService/i");
            })  
            ->whereHas('facility', function ($query) use ($searchPartenaire) {
                $query->addSelect('id','name')->where('name', 'regexp', "/$searchPartenaire/i");
            })
            ->whereHas('conciergeries.network', function ($query) use ($searchFiliale) {
                $query->addSelect('id','name')->where('name', 'regexp', "/$searchFiliale/i");
            })
                ->where('name', 'regexp', "/$search/i")
                ->orderBy($orderBy, $orderDirection)
                ->paginate(50);

I want get only names and ids of "service", "facility" and "conciegeries.network".
I tried to use select('id','name'); and select(['id','name']); or addSelect('id','name'); and pluck('id', 'name'); but i get all datas.
Do you have alternatives solutions ?
Thank you !

答案1

得分: 2

Select需要添加到with中,而不是whereHas。尝试使用以下代码:

Prestation::with([
    'service' => function($query) { 
        $query->select(['id', 'name']);
    },
    'facility' => function($query) { 
        $query->select(['id', 'name']);
    },
    'conciergeries.network' => function($query) { 
        $query->select(['id', 'name']);
    }
])
英文:

Select needs to be added to with, not whereHas. Try this instead:

Prestation::with(['service' => function($query) { $query->select(['id','name']);},
    'facility' => function($query) { $query->select(['id','name']);},
    'conciergeries.network' => function($query) { $query->select(['id','name']);}
])

huangapple
  • 本文由 发表于 2020年1月3日 23:46:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/59581424.html
匿名

发表评论

匿名网友

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

确定