如何使用laravel查询构建器编写此查询?

时间:2017-05-03 00:04:53

标签: laravel laravel-5

我在laravel 5.1上使用postgres作为数据库。我有一个小提琴,以防它有助于理解我的问题:https://www.db-fiddle.com/f/5ELU6xinJrXiQJ6u6VH5/4

with properties as (
    select 
        properties.*, 
        json_agg(property_fields.*) as property_fields 
    from 
        properties 
    left join fields as property_fields 
        on property_fields.parent = 'property' and property_fields.parent_id = properties.id 
    group by properties.id, properties.deal_id, properties.address
)

select 
    deals.*, 
    json_agg(properties.*) as deal_properties, 
    json_agg(deal_fields.*) as deal_fields
from deals

left join properties on deals.id = properties.deal_id
left join fields deal_fields on deal_fields.parent = 'deal' and deal_fields.parent_id = deals.id

group by deals.id, deals.name
order by deals.id

写下大部分内容非常简单。我遇到的问题是with properties as (...)阻止。我尝试过类似的事情:

DB::statement('WITH properties AS ( ... )')
    ->table('deals')
    ->select(' deals.*, json_agg(properties.*) as deal_properties,  ')
    ...
    ->get();

但我注意到DB::statement()

之后执行停止了

查询生成器中是否存在我丢失的方法?如何使用WITH properties AS (...)语句为查询添加前缀?

我认为还应该注意的是,我正在尝试实现存储库模式,而我无法在整个查询中包含DB::statement()

3 个答案:

答案 0 :(得分:0)

I've created a package for common table expressions: https://github.com/staudenmeir/laravel-cte

$query = 'select properties.*, [...]';

DB::table('deals')
    ->withExpression('properties', $query)
    ->leftJoin([...])
    ->[...]

You can also provide a query builder instance:

$query = DB::table('properties')
    ->select('properties.*', [...])
    ->leftJoin([...])
    ->[...]

DB::table('deals')
    ->withExpression('properties', $query)
    ->leftJoin([...])
    ->[...]

答案 1 :(得分:-1)

如果你想从表中获取一些数据,你可以使用这种类型的代码

$user = DB::table('table name')->where('name', 'John')->where('height','!>',"7")->select('table fields which you want to fetch')->get();

或尝试使用lalovel Eloquent ORM,这将使数据库更容易。

更多示例或参考

https://laravel.com/docs/5.0/queries

答案 2 :(得分:-1)

我认为你可以通过热切加载实际做到这一点,  假设关系设置正确。  (更多阅读:https://laravel.com/docs/5.4/eloquent-relationships#constraining-eager-loads

所以我认为你可以添加像

这样的东西
->with(['properties' => function ($query) {
    $query->select('field')
        ->leftJoin('join statement')
        ->groupBy('field1', 'field2');
}])