mysql Laravel雄辩的查询BelngsToMany透视表

eqzww0vc  于 8个月前  发布在  Mysql
关注(0)|答案(2)|浏览(82)

我正在尝试为一个BelongsToMany关系编写一个Eloquent查询,其中的结果只返回一个基于透视表的不同结果。

| ID|名称|
| --|--|
| 1 |第1章|
| 2 |安装程序2|
州:
| ID|名称|
| --|--|
| 1 |状态1|
| 2 |状态2|
枢轴:
| ID|状态Id| Id|基线|创建|
| --|--|--|--|--|
| 1 | 1 | 1 |1.0版|2023-01-01 2023-01-01|
| 2 | 1 | 1 |1.2| 2023-01-02 2023-01-02|
| 3 | 2 | 1 |一点五|2023-01-01 2023-01-01|
因此,我想运行查询$state->installers()->get(),其中,使用上面的例子,ID 1只返回ID 2和3。我不想要ID 1的原因是因为它是在列创建的旧记录。我可以完成这一点的唯一方法是使用连接吗?不是雄辩的ORM?

qoefvg9y

qoefvg9y1#

您可以应用子查询来加载某个州的最新不同安装程序。
例如,如下所示

$states = State::with(['installers' => function ($query) {
    $query->select(['installer_id', \DB::raw('MAX(created_at) as latest_created_at')])
        ->groupBy('installer_id')
        ->orderBy('latest_created_at', 'desc');
}])->find($state_id);

字符串
$states->installers将包含指定状态的最新非重复安装记录。

flseospp

flseospp2#

我理解你的问题和透视表的关系,我找到了这个解决方案:
用Eloquent试试这个原始的SQL join

$state = State::find($stateId); // Replace $stateId with the ID of the state you want to retrieve data for.

$installers = Installer::select('installers.id', 'installers.name')
    ->join('installer_state', 'installers.id', '=', 'installer_state.installer_id')
    ->where('installer_state.state_id', $stateId)
    ->orderBy('installer_state.created_at', 'desc')
    ->distinct()
    ->get();

字符串
此查询将返回$stateId的数据,其中首先检查$stateId的条件,并获取orderBy created_date字段中具有distinct值的数据。
我希望这对你有用。

相关问题