0

I have set of users, customers and they are related, and it will change every month, my requirement is get active month user for customers.

My Customer Model


public function executives()
    {
        return $this->belongsToMany(User::class, 'user_customer_mapping', 'user_customer_mapping_customer_id', 'user_customer_mapping_user_id');
    }


user_customer_mapping table have a Column for month with values like (Y-m), i need to find "2020-10" executive for all customers


$month= '2020-10';
$Executive = $customer->executives()->where('user_farmer_mapping_season', $month)->first();
return ($fieldExecutive) ? $fieldExecutive->name : 'N/A';

1 Answer 1

1

Start by adding withPivot to your relationship so the additional pivot table columns are loaded also:

public function executives()
{
    return $this->belongsToMany(User::class, 'user_customer_mapping', 'user_customer_mapping_customer_id', 'user_customer_mapping_user_id')
                ->withPivot('month');
}

Next, use wherePivot to query against the pivot table column(s):

$month= '2020-10';
$Executive = $customer->executives()->wherePivot('month', $month)->first();
return ($fieldExecutive) ? $fieldExecutive->name : 'N/A';
Sign up to request clarification or add additional context in comments.

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.