我有两个实体:项目和投标,每个项目都有很多投标,因此投标是项目的集合属性。
在显示项目的页面中,我只想显示有关此“项目”的出价的前10条记录。
所以,我这样做查询:
from item
left join fetch item.bids
where item.id=3
...
Run Code Online (Sandbox Code Playgroud)
但这将获取有关某个项目的所有出价,因此,如何限制该项目的出价?
我们有一个示例模型:
#models.py
class Author(models.Model):
name = models.CharField(max_length=255)
class Book(models.Model):
name = models.CharField(max_length=255)
author = models.ManyToManyField(Author, blank=True)
def get_authors(self):
return self.authors.all().order_by('id').values_list('name')
#views.py
class BooksView(ListView):
model = Book
def get_queryset(self):
q = Book.select_related('authors').all()
#template
{% for book in books %}
{{ book.name }} ({%for author in book.get_authors %} {{ author }} {% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用get_authors函数从模板获取数据时,我看到多个SQL查询会大大降低性能(SQL工作大约5秒).是否可以减少查询?现在我在循环中看到每个作者的SQL查询.
from sqlalchemy.orm import subqueryload, joinedload, eagerload
from sqlalchemy import Column, DateTime, String, Integer, ForeignKey, func,Float, sql
from sqlalchemy.orm import relation
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
engine = create_engine('sqlite:///testdb.sqlite')
engine.echo = True
Base = declarative_base()
session = sessionmaker()
session.configure(bind=engine)
Base.metadata.create_all(engine)
s= session()
class Stock(Base):
__tablename__ = 'stock'
stock_id = Column(Integer, primary_key=True)
name = Column(String)
prices = relation("StockPrice")
class StockPrice(Base):
__tablename__ = 'stock_price'
stock_id = Column(Integer, ForeignKey('stock.stock_id'), primary_key=True)
date = Column(String, primary_key=True)
price = Column(Float) …Run Code Online (Sandbox Code Playgroud) 我正在我的项目中处理某种"复杂"的表单,其中实体在每个步骤上都是持久的,因为各个表单都是分开的.然后我迈出了第一步(让我们称之为步骤1),我坚持一个实体并将其存储在会话中,请参阅下面的代码:
$productoSolicitudEntity = new Entity\ProductoSolicitud();
$productoSolicitudForm = $this->createForm(new Form\ProductoSolicitudForm(), $productoSolicitudEntity);
$productoSolicitudForm->handleRequest($request);
if ($productoSolicitudForm->isValid()) {
$productoSolicitudRequest = $request->get('productoSolicitud');
try {
$producto = $em->getRepository("AppBundle:Producto")->find($productoSolicitudRequest['producto']['nombre']);
$productoSolicitudEntity->setProducto($producto);
$condicionProducto = $em->getRepository("AppBundle:CondicionProducto")->find($productoSolicitudRequest['condicion_producto']);
$productoSolicitudEntity->setCondicionProducto($condicionProducto);
$finalidadProducto = $em->getRepository("AppBundle:FinalidadProducto")->find($productoSolicitudRequest['finalidad_producto']);
$productoSolicitudEntity->setFinalidadProducto($finalidadProducto);
$procedenciaProducto = $em->getRepository("AppBundle:ProcedenciaProducto")->find($productoSolicitudRequest['procedencia_producto']);
$productoSolicitudEntity->setProcedenciaProducto($procedenciaProducto);
$productoSolicitudEntity->setLote($productoSolicitudRequest['lote']);
$solicitudUsuario = $em->getRepository("AppBundle:SolicitudUsuario")->find($session->get('solicitudUsuarioEntity')->getId());
$productoSolicitudEntity->setSolicitudUsuario($solicitudUsuario);
$em->persist($productoSolicitudEntity);
$em->flush();
$session->set('productoSolicitudEntity', $productoSolicitudEntity);
$response['success'] = true;
} catch (Exception $ex) {
$status = 400;
$response['error'] = $ex->getMessage();
}
} else {
$status = 400;
$response['error'] = $this->get('translator')->trans('formularioNoValido');
$response['formError'] = $this->getFormErrors($productoSolicitudForm);
}
Run Code Online (Sandbox Code Playgroud)
然后在四个步骤(让我们称之为步骤4)我需要将该实体附加到一个新实体,因为它们是相关的,这是涉及的代码:
$productoSolicitud = $session->get('productoSolicitudEntity');
if (! $productoSolicitud) { …Run Code Online (Sandbox Code Playgroud) 我很好奇地看到如何从n到kth获得记录.我不知道我是否错过了,但是通过文档并没有对我有利.
我不是说我想要记录,其中id介于5 - 10之间,但记录介于5 - 10之间.如何进行此操作?
我在使用CFC组件时在ColdFusion中编写了一些代码,当我对使用不同方法创建组件对象感到困惑时.如果有人请让我知道创建对象的哪种方法更好,我将不胜感激.
CreateObject(),EntityNew()&& Newkeyword.我阅读了几篇博客并得到了不同的答案,有些人表示,与Create Object相比,Entity New更快.我还发现语法上的差异更好EntityNew().如果我能从任何人那里得到一些想法,我将不胜感激.谢谢.
这是我在DynamicViewsTable.php中的自定义finder方法
public function findAccessibleByUser(Query $query, array $options)
{
if (empty($options['User']['id'])) {
throw new Exception("Current User not set", 1);
}
$query->select(['DynamicViews.id', 'DynamicViews.title', 'UsersAccessDynamicViews.ordinal_ranking'])
->contain(['UsersAccessDynamicViews'])
->where([
'UsersAccessDynamicViews.user_id' => $options['User']['id'],
])
->order(['UsersAccessDynamicViews.ordinal_ranking' => 'ASC']);
return $query;
}
Run Code Online (Sandbox Code Playgroud)
我一直得到的错误是:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'UsersAccessDynamicViews.ordinal_ranking' in 'field list'
Run Code Online (Sandbox Code Playgroud)
并且错误页面中显示的查询是:
SELECT DynamicViews.id AS `DynamicViews__id`, DynamicViews.title AS `DynamicViews__title`, UsersAccessDynamicViews.ordinal_ranking AS `UsersAccessDynamicViews__ordinal_ranking` FROM dynamic_views DynamicViews WHERE UsersAccessDynamicViews.user_id = :c0 ORDER BY UsersAccessDynamicViews.ordinal_ranking ASC
Run Code Online (Sandbox Code Playgroud)
DynamicViews拥有许多UsersAccessDynamicViews
我试图在Hibernate中使用FetchMode.JOIN来理解但面临某些问题.我有3个班级,员工和员工主类.部门与员工有一个关系.
以下是代码部门类: -
@Entity
@Table(name="DEPARTMENT")
public class Department {
@Id
@GeneratedValue
@Column(name="DEPARTMENT_ID")
private Long departmentId;
@Column(name="DEPT_NAME")
private String departmentName;
@OneToMany(mappedBy="department")
@Fetch(FetchMode.JOIN)
private List<Employee> employees = new ArrayList<>();
public Long getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Long departmentId) {
this.departmentId = departmentId;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
Run Code Online (Sandbox Code Playgroud)
员工类: -
@Entity
@Table(name="EMPLOYEE") …Run Code Online (Sandbox Code Playgroud) 我想知道在Waterline中是否可以定义模型或按照Node-ORM2中的名称获取模型.
定义:
var Person = db.define("person", {
name : String,
surname : String,
age : Number, // FLOAT
male : Boolean,
continent : [ "Europe", "America", "Asia", "Africa", "Australia", "Antartica" ], // ENUM type
photo : Buffer, // BLOB/BINARY
data : Object // JSON encoded
}, {
methods: {
fullName: function () {
return this.name + ' ' + this.surname;
}
},
validations: {
age: orm.enforce.ranges.number(18, undefined, "under-age")
}
});
Run Code Online (Sandbox Code Playgroud)
获得:
var MyPersonModel = db.models["person"];
Run Code Online (Sandbox Code Playgroud)
谢谢!
我在基本字段中有类型datetime,它是time字段.我希望从基础获得所有元素并获得额外的timeu字段 - 它是UNIX_TIMESTAMP(time).我试着通过添加来做到这一点,->select('*','UNIXTIMESTAMP(time) AS timeu')但是Laravel给了我错误.我需要它用于->keyBy().我有下一个错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'UNIX_TIMESTAMP(time)' in 'field list' (SQL: select *, `UNIX_TIMESTAMP(time)` as `timeu` from `values` where UNIX_TIMESTAMP(time) <= 1429135199 and UNIX_TIMESTAMP(time) >= 1428444000 order by `id` asc)
Run Code Online (Sandbox Code Playgroud)
我该如何解决?
orm ×10
php ×3
hibernate ×2
java ×2
activerecord ×1
cakephp-3.0 ×1
coldfusion ×1
createobject ×1
database ×1
django ×1
doctrine-orm ×1
javascript ×1
jpa ×1
laravel ×1
laravel-5 ×1
node.js ×1
python ×1
ruby ×1
sails.js ×1
sinatra ×1
sql ×1
sqlalchemy ×1
symfony ×1
waterline ×1