简体   繁体   中英

Laravel eloquent difficult relation query

I'm a system for a friend, but stumbled across a little problem. I've got 3 models (customerCard, customerCardComment and customerCardFollowup).

It's better if you see the image below to understand what I'm trying to achieve. As you see I'm trying to get a result where I get a customerCard model where the sold field is equal to 0 and the customerCard model has no customerCardComment model where the type field is equal to 1,2 or 3, and the customerCard also does not have any customerCardFollowup.

Databases: customer_cards customer_card_comments customer_card_followups

Both comments and followups table are related to the ID field in customer_cards. Both have foreign keys customer_card_id.

Is there a way to do this query? Or am i lost? Thanks in advance.

在此处输入图片说明

Laravel's whereHas accepts a 3rd and 4th parameter. The 3rd parameter is the comparison operator against the count of the result set, and the 4th argument is the number to compare against. This will solve the first problem:

CustomerCard::where(function($query){
    $query->where('sold', 0)
         ->whereHas('customerCardComment', function($query){
             return $query->whereIn('type', [1,2,3]);
         }, '=', 0);
});

Next, you can use ->has() to count the number of records returned from a relation, this will solve your second problem:

CustomerCard::where(function($query){
    $query->where('sold', 0)
         ->whereHas('customerCardComment', function($query){
             return $query->whereIn('type', [1,2,3]);
         }, '=',  0)
         ->has('customerCardFollowup', '=', 0);
});

The 3rd one is actually a bit more complex and I need to think about how to approach that a bit more. I'll answer now to get you going in the right direction and edit and update the post with the solution to the 3rd problem shortly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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