gpt4 book ai didi

php - laravel 一起使用 with() , pluck()

转载 作者:可可西里 更新时间:2023-10-31 23:27:51 25 4
gpt4 key购买 nike

Query Output

\App\Post :

function PostMeta(){
return $this->hasMany('App\PostMeta');
}

我的查询:( pluck 不工作)-

I need to use less database queries

$query = \App\Post
::with(array('PostMeta'=>function($query){
$query->pluck('key','value');
}));
$query->get();

我需要得到 title_en ,但是我不能在这里使用 pluck!

新更新

已解决:

function get_PostMeta(){
// print_r($this->relations['PostMeta']);
return $this->relations['PostMeta'];
}


$query = \App\Post::with('PostMeta')->get();
foreach ($query as $key => $post){
$post->meta = $post->get_PostMeta()->pluck('value', 'key');
}

最佳答案

你不能在急切加载数据时这样做,但你可以在访问关系数据时在 View 中使用同名的集合方法pluck():

{{ $post->postMeta->pluck('value', 'key') }}

在这种情况下,您将避免 N+1 问题并以您想要的格式获取数据。

更新

既然你想为 Vue 准备数据,下面是一个如何迭代集合的小例子:

foreach ($posts as $post) {
$post->meta = $post->postMeta->pluck('value', 'key');
unset($post->postMeta);
}

关于php - laravel 一起使用 with() , pluck(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43570385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com