基于透视表获取结果


getting results based on a pivot table

我正试图根据数据透视表中的值从数据库中提取数据。

这些是我的桌子:

uploads
-> id
-> name
-> type
emails
-> id
-> email

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

例如,现在我有以下url:1234

如何选择附加到数据透视表'upload_email'的上载其中数据透视表中的url值与1234 匹配

我有以下

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

但这根本不起作用。我确实在我的模型等中建立了关系…

编辑:

根据建议的答案,我非常接近。这就是我现在拥有的:

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

我的数据库中有9个上传。当我使用上面的查询时,它会返回所有上传的邮件,但这些邮件只包含在匹配的pivot url中。但这不是我想要的,我只想上传一次。pivot url与我的值匹配的那个。

根据您的表,您只需要修复以下问题:

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

您可能需要使用with方法的热切加载约束:

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

查看文档了解更多信息。

试试这个:

$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();

钞票

由于wherePivotorWherePivot已可用,请参阅此处。

你必须在你的关系中添加额外的列,如下所示:

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

假设使用Laravel 4.1,您可以为您的模型添加另一种方法:

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