是否可以加入两个单独的查询调用?更具体地说,是否可以加入$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
我正在尝试避免进行另一个复杂的查询。 我尝试运行联合,但遇到绑定错误,我也尝试执行以下类似操作,但这并没有达到预期的结果。
foreach($servers as $server){
$applications->add($server);
}
$test = $applications->toarray();
dd($test);
有没有人对我什至可以做到这一点有任何想法?还是我必须对所有5个表进行查询?
(如果需要,将进行迁移)
编辑::
为清楚起见,我尝试在应用程序联接表中的status
查询之后获取服务器的$servers
列。
答案 0 :(得分:0)
使用此查询解决了该问题。
$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();
答案 1 :(得分:-2)
使用可以使用eloquent relationships,让Laravel为您完成艰苦的工作。
对于您而言,您可以执行以下操作:
Apps.php
public function servers() {
return $this->belongsToMany(Server::class, 'app_servers', 'app_id', 'server_id');
}
Server.php
public function statuses () {
return $this->belongsToMany(Status::class, 'server_statuses', 'server_id', 'status_id');
}
控制器
$applications = Apps::with('servers.status')->get();
// now use the data however you want.
foreach($applications as $application) {
foreach($application->servers as $server) {
dd($server->statuses);
}
}