【问题标题】:transform raw query with subqueries to eloquent将带有子查询的原始查询转换为 eloquent
【发布时间】:2017-07-28 09:58:35
【问题描述】:

我有以下工作查询和一个工作正常的子查询我想转换到 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 table) 表示的 User 模型和一个由 (properites table) 表示的 Property 模型

User -> Property 关系是一对多

用户

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

属性

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

输出应返回所有拥有一个属性且属性与当前日期匹配的用户。

在用于测试目的的原始查询中,我使用的是常量年份

【问题讨论】:

  • 请发布您的表结构并发布您预期的查询输出。

标签: mysql laravel-5 eloquent


【解决方案1】:

实际上看起来像

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

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

        })->get();

【讨论】:

    猜你喜欢
    • 2018-09-12
    • 2019-04-29
    • 2016-04-27
    • 2019-05-31
    • 2019-04-04
    • 2021-09-02
    • 2021-09-11
    • 2018-01-04
    • 2020-02-07
    相关资源
    最近更新 更多