gpt4 book ai didi

mysql - Laravel 5,加入两个单独的查询调用?

转载 作者:行者123 更新时间:2023-11-29 17:20:49 25 4
gpt4 key购买 nike

是否可以加入两个单独的查询调用?更具体地说,是否可以加入 $servers$applications

$servers = Server::select('servers.*', 'statuses.status as status_name')
->leftJoin('server_statuses', function($join) {
$join->on('server_statuses.server_id', '=', 'servers.id')
->where('server_statuses.id', function($query) {
$query->select('id')
->from('server_statuses')
->whereColumn('server_id', 'servers.id')
->latest()
->limit(1);
});
})
->leftJoin('statuses', 'statuses.id', '=', 'server_statuses.status_id')
->where('servers.isPublic', '=', 1)
->orderBy('servers.id', 'desc')
->get();

$applications = Apps::join('app_servers', 'apps.id', '=', 'app_servers.app_id')
->get();

$servers查询正在执行以下sql语句:

select `servers`.*, `statuses`.`status` as `status_name` from `servers` left join `server_statuses` on `server_statuses`.`server_id` = `servers`.`id` and `server_statuses`.`id` = (select `id` from `server_statuses` where `server_id` = `servers`.`id` order by `created_at` desc limit 1) left join `statuses` on `statuses`.`id` = `server_statuses`.`status_id` where `servers`.`isPublic` = '1' order by `servers`.`id` desc

我试图避免再次出现复杂的查询。我尝试运行联合,但遇到绑定(bind)错误,我也尝试执行类似下面的操作,但这并没有给我预期的结果。

foreach($servers as $server){
$applications->add($server);
}

$test = $applications->toarray();

dd($test);

如果可能的话,有人知道我该如何实现这一目标吗?或者我必须对所有 5 个表进行查询吗?

(如果需要,将发布迁移)

编辑::

为了清楚起见,我试图在应用程序联接表中的 $servers 查询之后获取服务器的 status 列。

最佳答案

使用此查询解决了它。

  $applications = Apps::select('apps.*')
->join('app_servers', 'app_servers.app_id', '=', 'apps.id')
->leftjoin('servers', 'app_servers.server_id', '=', 'servers.id')
->select('servers.*', 'statuses.status as status_name')
->leftJoin('server_statuses', function($join) {
$join->on('server_statuses.server_id', '=', 'servers.id')
->where('server_statuses.id', function($query) {
$query->select('id')
->from('server_statuses')
->whereColumn('server_id', 'servers.id')
->latest()
->limit(1);
});
})
->leftJoin('statuses', 'statuses.id', '=', 'server_statuses.status_id')
->select('apps.id', 'servers.id', 'apps.name', 'statuses.status', 'servers.name as sn', 'server_statuses.created_at')
->orderBy('apps.id', 'desc')
->get();

关于mysql - Laravel 5,加入两个单独的查询调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51267988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com