简体   繁体   English

Laravel中数据库查询构建器的位置

[英]Place for database query builder in Laravel

I can use scopes to perform basic model-related queries (such as select those users who have a birthday today), scopes are obviously placed in Eloquent Models and return an instance of Eloquent Query Builder. 我可以使用范围执行与模型相关的基本查询(例如选择今天有生日的那些用户),范围显然放置在Eloquent模型中,并返回Eloquent Query Builder的实例。 But what if I need to perform a more complex query, say group a massive email log table by email type, join with users and emails and apply some aggregates? 但是,如果我需要执行更复杂的查询,例如按电子邮件类型对海量电子邮件日志表进行分组,与用户和电子邮件连接并应用一些汇总,该怎么办? Since the resulting fields of the query are mixed (email, email type, user, log fields), I have to use Database Query Builder. 由于查询的结果字段是混合的(电子邮件,电子邮件类型,用户,日志字段),因此我必须使用数据库查询生成器。 I'm hesitating thinking of the best place for the call to the builder. 我犹豫要不要打电话给建造者。

Is can be a static method in the main model where I join other tables to: 在主要模型中,Is可以是静态方法,在该模型中我将其他表连接到:

    class ConcreteModel extends Model {

      public static function someQuery(): \Illuminate\Database\Query\Builder {
        return \DB::table('some_table')->join('something');
      }

    }

Or maybe rather to place such stuff in services that need it? 还是宁愿将此类内容放入需要的服务中?

Well I've come up with the idea of using the Visitor pattern for encapsulating complex queries. 好吧,我想到了使用Visitor模式封装复杂查询的想法。 Visitor objects encapsulate concrete queries, eloquent models can accept visitors passed by the client and invoke standard methods on them passing themselves to the visitor and handing over collections of StdClasses with results from the visitor back to the client. 访问者对象封装了具体的查询,雄辩的模型可以接受客户端传递的访问者,并在其上调用标准方法,将自身传递给访问者,并将StdClasses的集合从访问者的结果移交给客户端。 Seems it can work out for me. 似乎可以为我解决。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM