2014-04-24 30 views
0

我试图从我的数据库中获取数据,这取决于数据透视表中的值。基于数据透视表获取结果

这些都是我的表:

uploads 
-> id 
-> name 
-> type 

emails 
-> id 
-> email 


upload_emails 
-> id 
-> upload_id 
-> email_id 
-> 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上传在我的数据库。当我使用上面的查询时,它会返回所有上传内容,但这些电子邮件只包含在匹配的枢纽网址中。但那不是我想要的,我只想要1上传。支点url匹配我的值的那个。使用with方法

+0

这不应该是一个多对多的关系吗? – majidarif

+0

它建立为多对多的关系。 – vincent

+0

也你在哪里得到'url'? – majidarif

回答

0

根据你的表你需要解决这个问题:

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 
+0

最后一个例子工作得很好,除了给我所有现有的上传,bu只包括电子邮件匹配的网址。我想要的只是获得匹配枢纽网址的上传 – vincent

+0

然后编辑我的答案。wherePivot()在whereHas中不起作用,所以你需要明确地命名该字段。 –

+0

我能说什么。像一个魅力,tyvm。 – vincent

0

预先加载的限制可能是你需要的东西:更多信息

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

检查the docs

0

试试这个:

$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已变得可用,见here

你必须额外列添加到你这样的关系:

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

据称与Laravel 4.1,您可以添加另一种方法模型:

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