gsk
gsk

Reputation: 2379

Querying relation with condition in Laravel5?

I have two tables,one is client and second one client_contacts. I want list all contacts with one primary contact,which can be identify by checking is_primary field in client_contacts page.I also want response in object form. My controller,

Client::with(array('contacts'))
                        ->findOrFail($id);

My client model

public function contacts() {
    return $this->hasMany('App\Model\ClientContact');
}

In my client contacts model

 public function clients() {
    return $this->belongsTo('App\Model\Client');
}

It returns all contacts for each clients,how can I put condition here and return result as object?

Upvotes: 0

Views: 1724

Answers (1)

The Alpha
The Alpha

Reputation: 146229

You may declare two extra relationship methods in your Client model, for example:

use ...Model;

class Client extends Model {
   // Will return a collection of ClientContact object or null (many-to-many)
   public function nonPrimaryContacts()
   {
       // Assumed is_primary is a boolean field, use whereNull('is_primary') if null
       return $this->hasMany('App\Model\ClientContact')->where('is_primary', false);
   }
   // Will return a single ClientContact object or null (one-to-many)
   public function primaryContact()
   {
       return $this->hasOne('App\Model\ClientContact')->where('is_primary', true);
   }
}

Then you may use something like this:

Client::with(['primaryContact', 'nonPrimaryContacts'])->findOrFail($id);

For all contacts, you may use your contacts method in Client model.

Upvotes: 3

Related Questions