0

Affiliate has many affiliatesHistory, affiliatesHistory belongs to affiliate, how to make the following query?

Take affiliates, where has affiliatesHistory, if affiliatesHistory records count is equal to 1, then do not take affiliatesHistory, which has status of uninstalled.

$affiliates = $user->affiliates()
        ->whereDoesntHave('affiliatesHistory', function ($q) {
        $q->where('affiliates_histories.status', 'Installed earlier')
 ->orWhere('affiliates_histories.status', 'Uninstalled / Installed earlier');

The following query works, but I need to not take those affiliates, where affiliatesHistory count is equal to 1 and the status is uninstalled.

Any help will be appriaciated.

1
  • did you try and left join with raw query if you want to follow in that way i can write a answer Commented Jan 12, 2021 at 17:31

2 Answers 2

0

So, for what I understand you want to get the affiliates which affiliatesHistory status is Installed earlier. If this is the case then try this:

$user_affiliates =  $user->affiliates(); 
$affiliates = $user_affiliates->whereHas('affiliatesHistory', function($q){
   $q->where('status', 'Installed earlier');
})->get();

dd($affiliates);

Sign up to request clarification or add additional context in comments.

Comments

0

For your case if there are more than one affiliatesHistory items then return else if there is only one affiliatesHistory then it should not contain Uninstalled status, I guess you can use conditional count to get desired results as

$affiliates = Affiliate::withCount([
    'affiliatesHistory',
    'affiliatesHistory as affiliatesHistoryUninstalled_count' => function ($query) {
        $query->where('status', 'Uninstalled');
    }
    ])->where('user_id', $user->id)
      ->havingRaw('affiliatesHistory_count > 1 OR (affiliatesHistory_count = 1 AND affiliatesHistoryUninstalled_count = 0)')
      ->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.