我有一个类似这样的查询:
$valid_statuses = array('1', '2', '3');
$results = User::with(['posts' => function($query) use ($valid_statuses) {
$query->whereIn('status', $valid_statuses);
}
])
->get();该表的示例如下所示:
+----+---------+--------+
| id | post_id | status |
+----+---------+--------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 1 |
| 4 | 2 | 3 |
+----+---------+--------+我需要查询做的是,如果post_id缺少valid_status,它需要将缺少的状态添加到查询结果中。输出的结果查询应该如下所示:
+----+---------+--------+
| id | post_id | status |
+----+---------+--------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 1 | 3 |
| 4 | 2 | 1 |
| 5 | 2 | 2 |
| 6 | 2 | 3 |
+----+---------+--------+我该怎么做呢?
发布于 2016-02-07 11:20:41
如果Post和Status模型之间是多对多关系,您可以这样做。
维护原始数据库记录:
foreach($valid_statuses as $status_id) {
$have_status = Post::whereHas('status_id', $status_id)->lists('id');
$need_status = Post::whereNotIn('id', $valid_posts)->lists('id');
Status::find($status_id)->posts()->sync($need_status, false);
}或者如果你不关心原始记录:
foreach($valid_statuses as $status_id) {
Status::find($status_id)->posts()->sync(Post::all()->lists('id'));
} https://stackoverflow.com/questions/35249060
复制相似问题