OrderByNeighborsCount appends ordering based on the number of neighbors. For example, order users by their number of posts.
(q *sql.Selector, s *Step, opts ...sql.OrderTermOption)
| 378 | // OrderByNeighborsCount appends ordering based on the number of neighbors. |
| 379 | // For example, order users by their number of posts. |
| 380 | func OrderByNeighborsCount(q *sql.Selector, s *Step, opts ...sql.OrderTermOption) { |
| 381 | var ( |
| 382 | join *sql.Selector |
| 383 | opt = sql.NewOrderTermOptions(opts...) |
| 384 | build = sql.Dialect(q.Dialect()) |
| 385 | ) |
| 386 | switch { |
| 387 | case s.FromEdgeOwner(): |
| 388 | // For M2O and O2O inverse, the FK resides in the same table. |
| 389 | // Hence, the order by is on the nullability of the column. |
| 390 | x := func(b *sql.Builder) { |
| 391 | b.Ident(s.From.Column) |
| 392 | if opt.Desc { |
| 393 | b.WriteOp(sql.OpNotNull) |
| 394 | } else { |
| 395 | b.WriteOp(sql.OpIsNull) |
| 396 | } |
| 397 | } |
| 398 | q.OrderExpr(build.Expr(x)) |
| 399 | case s.ThroughEdgeTable(): |
| 400 | countAs := countAlias(q, s, opt) |
| 401 | terms := []sql.OrderTerm{ |
| 402 | sql.OrderByCount("*", append([]sql.OrderTermOption{sql.OrderAs(countAs)}, opts...)...), |
| 403 | } |
| 404 | pk1 := s.Edge.Columns[0] |
| 405 | if s.Edge.Inverse { |
| 406 | pk1 = s.Edge.Columns[1] |
| 407 | } |
| 408 | joinT := build.Table(s.Edge.Table).Schema(s.Edge.Schema) |
| 409 | join = build.Select( |
| 410 | joinT.C(pk1), |
| 411 | ).From(joinT).GroupBy(joinT.C(pk1)) |
| 412 | selectTerms(join, terms) |
| 413 | q.LeftJoin(join). |
| 414 | On( |
| 415 | q.C(s.From.Column), |
| 416 | join.C(pk1), |
| 417 | ) |
| 418 | orderTerms(q, join, terms) |
| 419 | case s.ToEdgeOwner(): |
| 420 | countAs := countAlias(q, s, opt) |
| 421 | terms := []sql.OrderTerm{ |
| 422 | sql.OrderByCount("*", append([]sql.OrderTermOption{sql.OrderAs(countAs)}, opts...)...), |
| 423 | } |
| 424 | edgeT := build.Table(s.Edge.Table).Schema(s.Edge.Schema) |
| 425 | join = build.Select( |
| 426 | edgeT.C(s.Edge.Columns[0]), |
| 427 | ).From(edgeT).GroupBy(edgeT.C(s.Edge.Columns[0])) |
| 428 | selectTerms(join, terms) |
| 429 | q.LeftJoin(join). |
| 430 | On( |
| 431 | q.C(s.From.Column), |
| 432 | join.C(s.Edge.Columns[0]), |
| 433 | ) |
| 434 | orderTerms(q, join, terms) |
| 435 | } |
| 436 | } |
| 437 |
searching dependent graphs…