4

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

我现在直接通过 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',
    // ...
  }
  // ...
}   
4

2 回答 2

-1

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

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

class Post extends Model
{
    // ...     

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

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

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

请参阅文档中的Eloquent Relations,尤其是 Eager Loading 部分。

于 2016-08-24T16:40:03.493 回答
-2

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

您需要在模型中为 Post 定义 Comment 函数

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

然后在你的控制器中

$result = Post::with('comments')->where('status', '=', 'PUBLIC')->select('comments')->get();
于 2016-08-24T16:41:04.253 回答