【问题标题】:Get only specific relations records仅获取特定的关系记录
【发布时间】:2020-02-17 20:19:05
【问题描述】:

我有一个客户模型和存款模型关系: 在存款模型表中,我有列:campaign_id 在我的客户端模型中:

public function deposits()
{
    return $this->hasMany(ClientDeposit::class, 'client_id');
}

我做简单的查询:


private function relations()
{
    return [
        'deposits',
    ];
}

$query->with($this->relations());

$query->whereHas('deposits', function ($query) {
   $query->where('campaign_id', '2');
})

此代码向我返回具有“campaign_id”、“2”的客户,但也有所有其他campaign_id 的存款

clients[0:{deposits: [id: 18507, client_id: 162186, user_id: 22, campaign_id: 2, amount: 100, method_id: null
0: {id: 18507, client_id: 162186, user_id: 22, campaign_id: 2, amount: 100, method_id: null,…}

1: {id: 18505, client_id: 162186, user_id: 22, campaign_id: 2, amount: 100, method_id: null,…}

2: {id: 18506, client_id: 162186, user_id: 22, campaign_id: 10, amount: 100, method_id: null,…}

3: {id: 18498, client_id: 162186, user_id: 22, campaign_id: 3, amount: 100, method_id: null,…}}]

我希望客户记录中的关系将只返回活动 ID 为 2 的存款,而不是所有其他相关的

【问题讨论】:

    标签: laravel laravel-5 eloquent


    【解决方案1】:
    $query->with([
        'deposits' => function($) {
            $q->where('campaign_id', '2');
        }
    ])
    

    【讨论】:

      猜你喜欢
      • 2019-06-12
      • 2015-07-23
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多