从查询转换为 Yii2 的 ModelSearch

Convert from query to ModelSearch of Yii2

我是 Yii2 的新手,我有一个正确结果的查询:

SELECT DISTINCT workloadTeam.project_id, wp.project_name, workloadTeam.user_id, workloadTeam.commit_time, wp.workload_type FROM 
(SELECT p.id, p.project_name, w.user_id, w.commit_time, w.comment, w.workload_type
     FROM workload as w, project as p
     WHERE w.user_id = 23 AND p.id = w.project_id) wp
INNER JOIN workload as workloadTeam ON wp.id = workloadTeam.project_id

但在我的 ModelSearch.php 中,我写道:

$user_id = Yii::$app->user->id;

$subquery = Workload::find()->select('p.id', 'p.project_name', 'w.user_id', 'w.commit_time', 'w.comment', 'w.workload_type')
        ->from(['project as p', 'workload as w'])
        ->where(['user_id' => $user_id, 'p.id' => 'w.project_id']);

$query = Workload::find()
        ->select(['workloadTeam.project_id', 'wp.project_name', 'workloadTeam.user_id', 'workloadTeam.from_date', 'workloadTeam.to_date', 'workloadTeam.workload_type', 'workloadTeam.comment'])
        ->where(['', '', $subquery]);

$query->join('INNER JOIN', 'workload as workloadTeam', 'wp.id = workloadTeam.project_id');

发生错误:

SELECT COUNT(*) FROM `workload` INNER JOIN `workload` `workloadTeam` ON wp.id = workloadTeam.project_id WHERE `` (SELECT p.project_name `p`.`id` FROM `project` `p`, `workload` `w` WHERE (`user_id`=20) AND (`p`.`id`='w.project_id'))

我无法用上面的正确查询修复它。 你有什么解决办法吗?

这个错误是否显示在 Yii-debug 工具栏中?那么您的查询(您提到的错误)可能只是之前列出的查询的计数。

您错过了在 from 子句中添加子查询,就像您在 sql 中显示的那样。在你的 where 子句中添加这个只是错误的地方。如果您有标量结果,请将子查询放在 where 条件中,因为您必须将此结果与 =>=in...[= 等操作数一起使用19=]

这可行:

$user_id = Yii::$app->user->id;

$subquery = Workload::find()->select([
    'p.id as id',
    'p.project_name as project_name',
    'w.user_id as user_id',
    'w.commit_time as commit_time',
    'w.comment as comment',
    'w.workload_type as workload_type'
])
->from([
    'project as p',
    'workload as w'
])
->where([
    'user_id' => $user_id,
    'p.id' => 'w.project_id'
]);

$query = Workload::find()
    ->select([
        'workloadTeam.project_id',
        'wp.project_name',
        'workloadTeam.user_id',
        'workloadTeam.from_date',
        'workloadTeam.to_date',
        'workloadTeam.workload_type',
        'workloadTeam.comment'
    ])
    ->from([$subquery => 'wp']); //you were missing this line

$query->join('INNER JOIN', 'workload as workloadTeam', 'wp.id = workloadTeam.project_id');

但是您没有在主查询中使用 workload table 中的任何选择 $query...

因为我不知道你要实现的目标是什么,所以我无法在这个话题上帮助你...