แปลงแบบสอบถามดิบด้วยแบบสอบถามย่อยให้เป็นคารมคมคาย

ฉันมีคำถามทำงานต่อไปนี้พร้อมแบบสอบถามย่อยซึ่งทำงานได้ดี ฉันต้องการเปลี่ยนจากเป็น Eloquent เพราะฉันต้องการที่จะสานต่อโมเดลผู้ใช้ของฉันต่อไป

select * from (
select p.from, a.account_id, count(*) as num
from accounts as a
inner join accounts_prop as p on (a.account_id = p.account_id)
group by p.account_id 
having num = 1 ) query

where year(query.von) = 2017

ฉันมีโมเดลผู้ใช้ที่แสดงโดย (accounts ตาราง) และโมเดลคุณสมบัติที่แสดงโดย (properites ตาราง) อยู่แล้ว

User -> Property ความสัมพันธ์เป็นแบบหนึ่งต่อหลายรายการ

ผู้ใช้

public function properties()
{
   return $this->hasMany('App\Property', 'account_id', 'account_id');
}

ทรัพย์สิน

  public function user()
    {
       return $this->belongsTo('App\User', 'account_id');
    }

ผลลัพธ์ควรส่งคืนผู้ใช้ทั้งหมดที่มีคุณสมบัติหนึ่งรายการและคุณสมบัติตรงกับวันที่ปัจจุบัน

ในแบบสอบถามดิบของฉันเพื่อการทดสอบฉันใช้ปีคงที่


person fefe    schedule 28.07.2017    source แหล่งที่มา
comment
กรุณาโพสต์โครงสร้างตารางของคุณและโพสต์ผลลัพธ์ของการสืบค้นที่คาดหวัง   -  person NikuNj Rathod    schedule 28.07.2017


คำตอบ (1)


จริงๆแล้วดูเหมือนว่าจะทำงานเหมือน

User::whereHas('properties', function($query){

            $query = $query->where('von', '=', Carbon::now()->format('Y-m-d'))
                           ->havingRaw('count(account_id) = 1')
                           ->with('department');

        })->get();
person fefe    schedule 30.07.2017