更复杂的续集选择
Sequel 中有一个简单的数据库:
DB = Sequel.sqlite
DB.create_table :items do
primary_key :id
DateTime :date
String :name
end
items = DB[:items]
items.insert(:name => 'abc', :date => DateTime.now)
items.insert(:name => 'ghi', :date => DateTime.now)
items.insert(:name => 'def', :date => DateTime.now)
问题:在数据库中存储“奇怪”的对象(例如 DateTime)是个好主意吗?
puts items.first(:name => 'ghi')[:date].year
输出“2010”,所以,好吧 - 它有效。但我还是很好奇。如果没什么不好的话,过滤一下怎么样?诸如此类的事情:
puts items.first(:date.year => 2010)[:name]
...行不通。是否可以通过其他方式做到这一点?如何?
There is a simple database in Sequel:
DB = Sequel.sqlite
DB.create_table :items do
primary_key :id
DateTime :date
String :name
end
items = DB[:items]
items.insert(:name => 'abc', :date => DateTime.now)
items.insert(:name => 'ghi', :date => DateTime.now)
items.insert(:name => 'def', :date => DateTime.now)
The question: is it a good idea to store 'strange' objects in database, like DateTime?
puts items.first(:name => 'ghi')[:date].year
Outputs '2010' so, well - it works. But still i'm quite curious about it. If it's nothing bad, what about filtering? Things like that:
puts items.first(:date.year => 2010)[:name]
... won't work. Is it possible to do it in other way? How?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
bjg是正确的。对于您的具体情况,而不是:
您可以尝试:
如果您的数据库支持 SQL 标准提取功能(并非所有数据库都支持),那么这应该可以工作。如果您的数据库没有,您将必须调用数据库中存在的任何类似函数。
bjg is correct. For your specific situation, instead of:
You could try:
Which should work if your database supports the SQL standard extract function (not all databases do). If your database does not, you'll have to call your whatever similar function exists for your database.
我认为您在这里问两个不同的问题:
在关系数据库中存储诸如日期之类的丰富对象是绝对正常的(大多数(如果不是全部)都支持日期等)。 Sequel 的
DateTime
属性类型承认了这一事实,并提供了对其所有支持的后端的抽象。过滤不太明显。不同的后端(读取数据库实现)将提供非常不同的分解方式,从而选择这些对象的各个部分。像 Sequel 这样的 ORM 必须绘制一些抽象线(希望)普遍适用于所有支持的后端。在某些情况下(
DateTime
很可能就是其中之一),更复杂的过滤将无法通过 ORM 的语法糖实现。在这种情况下,您可能需要深入到每个数据库的 SQL 工具来实现您想要的,或者至少在形成语法糖解决方案时了解底层语义I think you're asking 2 different questions here:
It's absolutely normal to store rich objects like dates in relational databases (most if not all support dates and the like). Sequel's
DateTime
attribute type is acknowledging this fact and provides an abstraction over all its supported back-ends.Filtering is less obvious. Different back-ends (read database implementations) will provide very different ways of decomposing and hence selecting parts of these objects. An ORM like Sequel has to draw some line of abstraction which is (hopefully) commonly applicable to all the supported back-ends. In some cases (and
DateTime
may well be one of them) the more sophisticated filtering will not be available via the ORM's syntactic sugar. You may, in such cases, need to drop down to the per-database SQL facility to achieve what you want, or at the very least, be aware of the underlying semantics when forming your syntactic sugar solution