Reached
5 months ago

Returning a single record instead of collection

Posted 5 months ago by Reached

Hi guys,

I am building an API where I have 3 different models:

Campaign Contract User

A Campaign can have many different Contract, belonging to many different User. A User can only have one Contract with the same Campaign at a time.

I am using a pivot table as an intermediary between Userand Contract.

I basically want to return a single Campaign with the Contract for the currently logged in user, however I think my relationships are setup wrong for this, because I get a collection of Contract belonging to a Campaign, when all I really want is just one Contract.

My current solution is to loop over all of the Contract and return the one that belongs to the User but that seems really inefficient to me..

My Campaign model:

class Campaign {
    public function contracts()
    {
        return $this->hasMany(Contract::class);
    }
}
    

My Contract model:

class Contract {
    public function campaign()
    {
        return $this->belongsTo(Campaign::class);
    }
}

My User model:

class User {
    public function contracts()
    {
        return $this->belongsToMany(Contract::class);
    }
}

I tried the following, but it returns a collection of contracts as mentioned above, not quite what I want. Any ideas here? :)

auth()->loginUsingId(1);
    return $campaign = \App\Campaign::with(['contracts.user' => function($query) {
        return $query->where('user_id', auth()->id());
    }])->find(2);

Please sign in or create an account to participate in this conversation.