我有这样的查询:
$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 |
+----+---------+--------+
我该怎么做?
答案 0 :(得分:0)
如果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'));
}