\App\Post :
function PostMeta(){
return $this->hasMany('App\PostMeta');
}
Run Code Online (Sandbox Code Playgroud)
而我的查询:( pluck 不起作用)-
我需要使用较少的数据库查询
$query = \App\Post
::with(array('PostMeta'=>function($query){
$query->pluck('key','value');
}));
$query->get();
Run Code Online (Sandbox Code Playgroud)
我需要得到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');
}
Run Code Online (Sandbox Code Playgroud)
在急切加载数据时无法执行此操作,但pluck()在访问关系数据时可以在视图中使用同名的集合方法:
{{ $post->postMeta->pluck('value', 'key') }}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您将避免 N+1 问题并以您想要的格式获取数据。
更新
由于您想要为 Vue 准备数据,因此这里有一个小示例,说明如何迭代集合:
foreach ($posts as $post) {
$post->meta = $post->postMeta->pluck('value', 'key');
unset($post->postMeta);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8258 次 |
| 最近记录: |