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

时间:2018-06-29 13:58:53

标签: php mysql laravel laravel-5 eloquent

现在,我正在运行一个子查询以获取服务器的最新状态,该子查询通过变量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(); 

我现在想要做的是对此进行连接,以便根据状态表中此查询的结果为我提供状态的实际名称。我试图做一个简单的左连接,但是却收到找不到last_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();
        });

Server_statuses表:

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的样子:

enter image description here

查询的原始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();

3 个答案:

答案 0 :(得分:2)

使用子查询WHERE子句组合LEFT JOIN:

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

答案 1 :(得分:1)

由于我不确定您想从查询中得到什么,我将提供一个长解决方案并添加一些示例。使用这些表,您应该具有以下模型: 服务器型号:

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

希望您能找到答案。

答案 2 :(得分:1)

据我了解,您的ServerStatus模型都与OneToManyServerStatus关系。在这种情况下,您可以在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关系一样。