سؤال

I'm trying to fetch data from my DB based on the value in my pivot table.

These are my tables:

uploads
-> id
-> name
-> type

emails
-> id
-> email


upload_emails
-> id
-> upload_id
-> email_id
-> url

Now for example I have the following url: 1234

How can I select the upload that is attached to the pivot table 'upload_email' where the url value in the pivot table matches 1234

I had the following

Upload::emails()->wherePivot('url', $key)->get();

But that's not working at all. I do have the relations set up in my model etc...

EDIT:

After the suggested answer I'm pretty close. This is what I have now:

return Upload::with(array('emails' => function($query) use ($key) {
    $query->wherePivot('url', $key);
}))->get();

I have 9 uploads in my database. When I use the query above, it returns all uploads, but the emails are only included on the matching pivot url. But that's not what I want, I only want 1 upload. The one where the pivot url matches my value.

هل كانت مفيدة؟

المحلول

According to your tables all you need is to fix this:

Upload::emails()->wherePivot('url', $key)->get(); // no url field on that table!
// change to:
Upload::find($id)->emails()->wherePivot('key', $key)->get();
// or if you want a collection then:
Upload::with(array('emails'=> function ($q) use ($key) {
   $qwherePivot('key', $key);
}))->get();

// to fetch only those Upload models that have related email matching given 'key'
Upload::whereHas('emails', function ($q) use ($key) {
   $q->where('upload_emails.key', $key);
})->get(); // add the above with(...) method to also load those emails

نصائح أخرى

Eager loading constraints using the with method could be what you need:

Upload::with('email', function($q) use($key) {
  $q->where('url', $key);
})->get();

check the docs for more info.

Try this:

$upload = Upload::with(array('email' => function($query) use ($key) {
   // where is URL in the table? shouldn't it be 'key'?
   $query->where('key', $key); 
}))->get();

notes

As wherePivot and orWherePivot has become available, see here.

You have to add the additional column to your relationship like this:

public function emails(){
    return $this->belongsToMany(...)->withPivot("key");
}

Supposedly with Laravel 4.1 you can add another method to your model:

$upload = Upload::emails()->wherePivot('key', $key)->get();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top