【问题标题】:Laravel query builder. Returning nested structured dataLaravel 查询生成器。返回嵌套结构化数据
【发布时间】:2016-12-31 20:07:52
【问题描述】:

我有一些查询需要一段时间,因为集合很大。

我现在在没有活动记录的情况下直接通过 Laravel 查询构建器进行操作。

将两个表连接在一起时,表 B 中的字段将合并到表 A 中的结果中。

是否可以将该数据嵌套在子对象或数组中?

例如

\DB::table('posts')
    ->select('posts.id', 'posts.title', 'comments.name', 'comments.id')
    ->where('posts.status', '=', 'PUBLIC')
    ->leftJoin('comments', 'posts.comment_id', '=', 'comments.id')
    ->get();

返回类似:

{
  id: 123,
  title: 'My post',
  name: 'Comment name',
  // ...
}   

我想去哪里:

{
  id: 123,
  title: 'My post',
  comment {
    name: 'Comment name',
    // ...
  }
  // ...
}   

【问题讨论】:

  • 你也有posts和cmets作为模型吗?您可能可以通过关系和with() 来做到这一点。
  • 如果不循环记录集并自己实现这个结构,我怀疑这是否可能。查询构建器只返回一个平面结果集,类似于您自己运行查询时所获得的结果。

标签: mysql database laravel eloquent laravel-5.3


【解决方案1】:

您可以通过 Eloquent 关系做到这一点。

首先,在模型中声明关系。例如,在 Post.php 中:

class Post extends Model
{
    // ...     

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

现在您可以在查询中使用with('comments')

它应该返回一个类似于你想要的对象。

请参阅文档中的 Eloquent Relationships,尤其是急切加载部分。

【讨论】:

  • 特地求查询生成器... 不是很有说服力
【解决方案2】:

我使用 with() 而不是查询生成器

你需要在你的模型中为 Post 定义一个 Comment 函数

public function posts(){
   return $this->belongsTo('App\Post', 'posts_id');
}

然后在你的控制器中

$result = Post::with('comments')->where('status', '=', 'PUBLIC')->select('comments')->get();

【讨论】:

  • 特意要求查询生成器不雄辩
猜你喜欢
  • 1970-01-01
  • 2018-06-02
  • 2017-05-26
  • 1970-01-01
  • 1970-01-01
  • 2021-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-16
相关资源
最近更新 更多