Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Laravel 如果不在where()中,则雄辩地创建列_Laravel_Laravel 4 - Fatal编程技术网

Laravel 如果不在where()中,则雄辩地创建列

Laravel 如果不在where()中,则雄辩地创建列,laravel,laravel-4,Laravel,Laravel 4,我有这样一个问题: $valid_statuses = array('1', '2', '3'); $results = User::with(['posts' => function($query) use ($valid_statuses) { $query->whereIn('status', $valid_statuses); } ]) ->get(); +----+---------+--------+ |

我有这样一个问题:

$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 |
+----+---------+--------+
该表的一个示例如下所示:

$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\u id
缺少
valid\u status
,它需要将缺少的状态添加到查询结果中。输出结果查询应如下所示:

+----+---------+--------+
| id | post_id | status |
+----+---------+--------+
|  1 |       1 |      1 |
|  2 |       1 |      2 |
|  3 |       1 |      3 |
|  4 |       2 |      1 |
|  5 |       2 |      2 |
|  6 |       2 |      3 |
+----+---------+--------+

我该怎么做呢?

如果帖子和状态模型之间存在多对多关系,您可以这样做

维护原始数据库记录:

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

是否要更新特定用户的所有帖子,使其具有所有3种状态,而您不知道哪些状态已创建?否,我想选择所有帖子,但如果该特定
帖子id
不存在该状态,请填写缺少的状态。i、 e.如果
post\u id
的状态为1和2,而不是3,则让查询将3添加到结果中。具有post\u id和状态的表的名称是什么?它有自己的型号吗?是否在Post模型中将其设置为归属关系?