Eloquent创建列,如果不在whereIn()

时间:2016-02-07 02:35:04

标签: laravel laravel-4

我有这样的查询:

$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 |
+----+---------+--------+

我该怎么做?

1 个答案:

答案 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'));
}