如何使用Laravel Eloquent编写SQL子查询?

时间:2019-02-08 13:36:05

标签: laravel

select properties.address, properties.unit_type, rents.date, rents.amount, lease_requests.security_deposit 
    from properties 
    left join rents on rents.property_id = properties.id 
    left join lease_requests on lease_requests.property_id = properties.id
    where (rents.status = 'paid' and rents.date between '2019-01-07' and '2019-02-07') 
    or (lease_requests.security_deposit_status = 'paid' and lease_requests.move_in between '2019-01-07' and '2019-02-07')

如何在Laravel中重写这个sql查询,而不是通过使用原始sql而是结合->join, ->where, ->orWhere来重写?我知道我应该在其中之一中使用函数,但是不确定在哪个函数中使用。所有这些函数都接受函数作为第二个参数吗?

编辑

这是我为完成此操作而编写的代码,但它并没有检索与我在此处编写的sql代码完全相同的数据,因为我不确定如何使用Laravel来使用方括号实现查询: / p>

Property::join('rents', 'properties.id', '=', 'rents.property_id')
            ->leftJoin('lease_requests', 'properties.id', '=', 'lease_requests.property_id')
            ->where('properties.address', $property['address'])
            ->whereBetween('move_in', [$from,$to])
            ->whereBetween('date', [$from,$to])
            ->where('rents.status', 'paid')
            ->orWhere('security_deposit_status', 'paid')
            ->get(['properties.address', 'properties.unit_type', 'rents.date', 'rents.amount', 'lease_requests.move_in', 'lease_requests.security_deposit'])->toArray();

1 个答案:

答案 0 :(得分:1)

$status = 'paid'; $dateStart = '2019-01-07'; $dateEnd = '2019-02-07';
DB::table('properties')
->selectRaw('properties.address, properties.unit_type, rents.date, rents.amount, lease_requests.security_deposit')
->leftJoin('rents', 'rents.property_id', '=', 'properties.id')
->leftJoin('lease_requests', 'lease_requests.property_id', '=', 'properties.id')
->where(function ($query) use ($status, $dateStart, $dateEnd)  {
    $query->where('rents.status', $status)->whereBetween('rents.date', [$dateStart, $dateEnd]);
})
->orWhere(function ($query) use ($status, $dateStart, $dateEnd)  {
    $query->where('lease_requests.security_deposit_status', $status)->whereBetween('lease_requests.move_in', [$dateStart, $dateEnd]);
})->get();

您必须提供一个获取括号的函数;)

编辑您的代码:

Property::leftJoin('rents', 'properties.id', '=', 'rents.property_id')
->leftJoin('lease_requests', 'properties.id', '=', 'lease_requests.property_id')
->where(function ($query) use ($status, $dateStart, $dateEnd)  {
    $query
          ->where('rents.status', $status)
          ->whereBetween('rents.date', [$dateStart, $dateEnd]);
})
->orWhere(function ($query) use ($status, $dateStart, $dateEnd)  {
    $query
          ->where('lease_requests.security_deposit_status', $status)
          ->whereBetween('lease_requests.move_in', [$dateStart, $dateEnd]);
})
->get([
    'properties.address', 'properties.unit_type',
    'rents.date', 'rents.amount', 'lease_requests.move_in', 
    'lease_requests.security_deposit'
])->toArray();