简体   繁体   English

Laravel雄辩的多张桌子

[英]Laravel Eloquent multiple tables

I have a complex setup which includes the following tables. 我有一个复杂的设置,其中包括以下表格。

Customers
Transactions
Jobs
Rounds
Job_Rounds

I want to output all the customers which are overdue. 我想输出所有过期的客户。 I've done that by using the following query: 我通过使用以下查询完成了此操作:

$data = Auth::user()->clients()->leftjoin('transactions','clients.id','=','transactions.client_id')
                ->select(DB::raw('sum(gross) as value, email, first_name, last_name, mobile, clients.id, addressline1'))
                ->groupBy('id','first_name','last_name','email','mobile','addressline1', 'clients.id')
                ->havingRaw('SUM(gross) < 0')
                ->get();

That returns all the customers which are overdue which is great, however I now want to be able to filter the overdue customers by round. 这将返回所有过期的客户,这很棒,但是我现在希望能够全面过滤过期的客户。

My relationships are as follows: 我的关系如下:

Customers > Jobs.client_id
Customers > Transactions.client_id
Jobs > Rounds via Jobs_Rounds

I would pass to my controller the round_id of a given round and then try to filter the results based on the round_id. 我将给定回合的round_id传递给我的控制器,然后尝试根据round_id过滤结果。 the only place I'm storing the round ID is in the jobs_rounds table and that table only contains job_id & round_id. 我存储回合ID的唯一位置是在jobs_rounds表中,该表仅包含job_id和round_id。

I'm thinking about using the HasManyThrough relationship to link a Customer and a Round . 我正在考虑使用HasManyThrough关系将CustomerRound关联起来。

Something like this : 像这样的东西:

// Customer.php
public function rounds()
{
    return $this->hasManyThrough(Round::class, Job::class, 'client_id', 'job_id', 'id');
}

Then in your controller you could try this : 然后,您可以在控制器中尝试以下操作:

$data = Auth::user()->clients()
            ->whereHas('rounds', function ($query) {
                $query->where('id', request()->input('round_id'))
            })
            //... the rest of your filters

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM