如何解决Yii:在加入之前执行where条件
我目前的查询有问题
public class Game {
private Scanner input = new Scanner(System.in); // Scanner reading from System.in
private int rounds; // 5-30
private int playerAmount; // Indicating how many players take part
private ArrayList<Player> players = new ArrayList<>(); // Storing player instances
public Game() {
System.out.println("Welcome to The Farm! Please enter how many will be playing today (1-4 players) by entering your names. When finished please enter menu to begin");
for(int i = 0; i < 4; i++) {
String name = input.readLine();
if (name.equals("menu") || players.size() >= 4) {
break; // User entered menu or the there are already 4 players in the ArrayList -> break out of the for loop
}
newPlayer(name); // New player gets added if the if-condition above isn't executed
}
playerAmount = players.size();
}
}
SQL查询的通常执行顺序是"menu"
,然后是TableA::find()
->select('*')
->joinWith(['TableB'])
->joinWith(['TableC'])
->joinWith(['TableD'])
->where([TableA.attribute1=1 or TableA.attribute2=1])
->andWhere([(further possible conditions on the other Tables)])
->all()
。
是否有一种方法可以在联接之前执行第一个where条件,以减少联接的行数?像
From (with joins)
解决方法
您可以修改用于联接表的条件。
在SQL中,它看起来像这样:
SELECT
*
FROM
`tableA`
JOIN `tableB` ON (
`tableA`.`FK` = `tableB`.`PK`
AND `tableA`.`attr1` = 'someValue'
)
JOIN tableC ON (`tableB`.`FK` = `tableC`.`PK`)
要在Yii中执行此操作,可以使用ActiveQuery::onCondition()
方法。如果只想对此查询应用此条件,则可以使用joinWith()
方法中的回调来修改用于联接的查询。
$query = TableA::find()
->joinWith([
'tableB' => function(\yii\db\ActiveQuery $query) {
$query->onCondition(['tableA.attr1' => 'someValue']);
}
])
//... the rest of query
其他选项将在SQL查询的FROM部分中使用子查询,如下所示:
SELECT
*
FROM
(
SELECT
*
FROM
`tableA`
WHERE
`attr1` = 'someValue'
) AS `tableA`
JOIN `tableB` ON (`tableA`.`FK` = `tableB`.`PK`)
在yii中:
$subQuery = TableA::find()
->select('*')
->where(['attr1' => 'someValue']);
$query = TableA::find()
->select('*')
->from(['tableA' => $subQuery])
->joinWith('tableB')
// ... the rest of query
此方法的主要缺点是子查询中的临时表将没有任何索引,因此联接和其他条件将变慢。如果tableA有很多行,并且在联接之前要应用的条件将显着减少行数,那么仍然可以使用这种方法。
,嗯,我认为这是最好的方法。但是,如果您不打印来自关系TableB
或TabelC
的数据(仅从条件中获取数据),则可以这样设置关系:
TableA::find()
->joinWith('TableB',false) //dont load data from this relational table
->joinWith('TableC',false) //dont load data from this relational table
->joinWith(['TableD']) //load data from this relational table
->where([TableA.attribute1=1 or TableA.attribute2=1])
->andWhere([(further possible conditions on the other Tables)])
->all()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。