簡體   English   中英

通過關系ID獲取模型

[英]Get Model by relationship ID's

我有一個Accomodation和一個Feature模型。 通過accomodation_feature數據透視表,住宿可以具有許多功能(廚房,陽台等):

//accomodation model
public function features()
{      
    return $this->belongsToMany('Feature');
}

我要選擇已激活所有選定功能的所有住宿。 例如,我想要所有帶陽台,廚房和微波爐的住宿。

我嘗試了以下方法,但得到的所有住宿都有陽台,廚房或微波爐:

$features = array("1", "2", "3"); //id's of the features I want to select

$accomodations = Accomodation
::whereHas('features', function($q) use ($features)
                {
                    $q->whereIn('features.id', $features);
                })                                
->get();

如何選擇具有所有提供的功能的所有住宿?

在此先感謝您的幫助,對於(可能)引起誤解的標題,我們深表歉意。 我想不出什么更合適的了。

使用whereHas()方法的額外參數:

whereHas($relation, Closure $callback, $operator = '>=', $count = 1)

即:

Accomodation::whereHas('features', function($q) use ($features) {
    $q->whereIn('features.id', $features);
}, '>=', count($features))->get();

其中絕對是錯的。 嘗試遍歷您的功能:

for each($features as feature)
    $q->where('features.id', feature);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM