php—是否可以对子查询创建的变量运行联接?

1tuwyuhd  于 2021-06-24  发布在  Mysql
关注(0)|答案(3)|浏览(287)

现在我运行一个子查询来获取服务器的最新状态,这个子查询通过变量返回 last_status .

//This is ran when WithLastStatusDate() is called
$query->addSubSelect('last_status', ServerStatus::select('status_id')
    ->whereRaw('server_id = servers.id')
    ->latest()
);

$servers = Server::WithLastStatusDate()
    ->OrderBy('servers.id', 'desc')
    ->where('servers.isPublic', '=', 1)
    ->get();

我现在要做的是对它执行一个join,这样它就会根据statuses表中的查询结果给出状态的实际名称。我试着做一个简单的左连接,但得到的错误是没有找到最后一个\u status列。

$servers = Server::WithLastStatusDate()
    ->OrderBy('servers.id', 'desc')
    ->where('servers.isPublic', '=', 1)
    ->leftjoin('statuses','servers.last_status', '=', 'statuses.id')
    ->get();

有谁能给我指出正确的方向来实现这个目标吗?
编辑:
服务器表:

Schema::create('servers', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->string('name');
            $table->string('url');
            $table->boolean('isPublic');
            $table->timestamps();
        });

服务器状态表:

Schema::create('server_statuses', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->increments('id');
            $table->integer('server_id')->unsigned();
            $table->foreign('server_id')->references('id')->on('servers')->onDelete('cascade');
            $table->integer('status_id')->unsigned();
            $table->foreign('status_id')->references('id')->on('statuses');
            $table->timestamps();
        });

状态表:

Schema::create('statuses', function (Blueprint $table) {
    $table->engine = 'InnoDB';
    $table->increments('id');
    $table->string('key');
    $table->string('status');
    $table->timestamps();
});

子查询后$servers的外观:

查询的原始sql:

select `servers`.*, (select `status_id` from `server_statuses` where server_id = servers.id order by `created_at` desc limit 1) as `last_status` from `servers` where `servers`.`isPublic` = '1' order by `servers`.`id` desc

编辑2::

$servers = DB::table('servers as sv')
        ->join('server_statuses as ss', 'sv.id', '=', 'ss.server_id')
        ->join('statuses as st', 'ss.status_id', '=', 'st.id')
        ->WithLastStatus()
        ->OrderBy('servers.id', 'desc')
        ->where('servers.isPublic', '=', 1)
        ->get();
zhte4eai

zhte4eai1#

因为我不确定你到底想从你的查询中得到什么,所以我将给出一个很长的解决方案并添加一些示例。有了这些表,您应该有以下模型:服务器模型:

class Server extends Model {
    public function statuses() {
        return $this->belongsToMany(Status::class, 'server_statuses');
    }
}

状态模型:

class Status extends Model {
    public function servers() {
        return $this->belongsToMany(Server::class, 'server_statuses');
    }
}

示例:获取服务器的最后状态:

Server::find($serverId)->statuses()->latest()->first()->status;

获取所有服务器状态:

Server::find($serverId)->statuses;

获取服务器的特定状态:

Server::find($serverId)->statuses()->where('status', 'SomeStatus')->get();

获取具有特定状态的服务器:

Server::whereHas('statuses', function ($join) use ($status) {
    return $join->where('status', $status);
})->get();

希望你能找到答案。

6vl6ewon

6vl6ewon2#

据我所知,你们两个 Server 以及 Status 模型有一个 OneToMany 关系 ServerStatus . 在这种情况下,你可以假装 OneToOne 你的关系 Server 被选为最新一行的模型 serverStatuses() :

class Server
{
    public function serverStatuses()
    {
        return $this->hasMany(ServerStatus::class, 'server_id', 'id');
    }

    public function latestServerStatus()
    {
        return $this->hasOne(ServerStatus::class, 'server_id', 'id')
            ->latest(); // this is the most important line of this example
                        // `->orderBy('created_at', 'desc')` would do the same
    }
}

class ServerStatus
{
    public function server()
    {
        return $this->belongsTo(Server::class, 'server_id', 'id');
    }

    public function status()
    {
        return $this->belongsTo(Status::class, 'status_id', 'id');
    }
}

class Status
{
    public function serverStatuses()
    {
        return $this->hasMany(ServerStatus::class, 'status_id', 'id');
    }
}

然后还可以加载服务器的最新状态以及状态本身:

Server::with('latestServerStatus.status')->get();

请注意 $server->latestServerStatus 不是集合而是一个对象,就像普通的 OneToOne 关系。

huwehgph

huwehgph3#

将左联接与子查询where子句组合:

$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();

相关问题