简体   繁体   English

Laravel雄辩的关系和在哪里

[英]Laravel Eloquent for relationships and whereHas

I have 2 tables clients & client_maintenance. 我有2个表client&client_maintenance。 They are joined using relationships so the client model hasMany client_maintenance & client_maintenance model belongsTo client 它们使用关系进行连接,因此客户端模型具有许多client_maintenance和client_maintenance模型属于客户端

This all seems to work find the issue is when I'm trying to get my data using eloquent. 这一切似乎都奏效,发现问题出在我试图使用雄辩的方式获取数据时。

Clients DB Table 客户数据库表

id | Name      
1    client 1   
2    client 2   
3    client 3   
4    client 4  

Client Maintenance Tabel 客户维护表

id | client_id (fk)| job          | date
1    3               something      2018-01-01
2    4               something      2017-12-23
3    4               something      2018-01-09
4    2               something      2018-01-05

Query 询问

$date_from = '2018-01-01';
$client = $request->get('client');


$clients = Client::where('id', '=', $client)->whereHas('client_maintenance', function($query) 
    {
        $query->when($date_from, function ($q) use ($date_from) {
            return $q->whereDate('date', '>=', $date_from);
        });
    })
    ->get();

The issue is when no matter what date is passed in all results for the client are returned. 问题是,无论经过什么日期,都将返回客户端的所有结果。 So I get both results with client_id 4 even though the one with date 2017 shoudln't be coming throguh. 因此,即使有日期为2017的结果也不会通过client_id 4得到两个结果。

the date_from variable contains data passed from a form on the frontend and contains valid data so thats not the issue, even if i set it manually like above I get the same results. date_from变量包含从前端表单传递的数据,并且包含有效数据,所以这不是问题,即使我像上面一样手动设置它,也得到相同的结果。

Any help would be great. 任何帮助都会很棒。

You need to use with() if you want to filter the client_maintenance table results: 如果要过滤client_maintenance表结果,则需要使用with()

$client = Client::with(['client_maintenance' => function($q) use($date_from) {
        $q->when($date_from, function ($q) use ($date_from) {
            return $q->whereDate('date', '>=', $date_from);
        });
    }])
    ->find($id);

Specify the relation name in where 在以下位置指定关系名称

$client = Client::with(['client_maintenance' => function($q) use($date_from) {
    $q->when($date_from, function ($q) use ($date_from) {
        return $q->whereDate('client_maintenance.date', '>=', $date_from);
    });
}])
->find($id);

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

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