Laravel 4 - 如何使用关系列的条件

Hil*_*Lam 6 where laravel laravel-4

这就是我想要的,我有两张桌子.一个是'餐馆',另一个是'设施'.

表很简单..和一对一的关系.像有一个餐桌id,name,slug,等,并叫另一台facilitiesid,restaurant_id,wifi,parking,等

这是我的模特:

class Restaurant extends Eloquent {

protected $table = 'restaurants';

public function facilities() {
    return $this->hasOne('Facilities'); 
}
}

class Facilities extends Eloquent {

protected $table = 'facilities';

public function restaurant() {
    return $this->belongsTo('Restaurant');
 }


}
Run Code Online (Sandbox Code Playgroud)

我想这样做Select * from restaurants r left join facilities rf on r.id=rf.restaurant_id where r.name = 'bbq' and rf.wifi != '1'.

如何使用Eloquent来做到这一点?

PS.抱歉修改自/sf/ask/1023536041/# =,但我遇到了类似的问题.

fid*_*per 12

您可以where在关系对象上使用和其他基于sql的方法.

这意味着您可以在模型中创建自定义方法:

class Restaurant extends Eloquent {

    protected $table = 'restaurants';

    public function facilities($wifi) {
        return $this->belongsTo('Facility')->where('wifi', '=', $wifi);
    }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以尝试使用查询范围:

class Restaurant extends Eloquent {

    protected $table = 'restaurants';

    public function facility() {
        return $this->belongsTo('Restaurant');
    }

    public function scopeFiltered($query, $wifi)
    {
        return $query->where('wifi', '>', 100);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

$wifi = 1;
$restaurants = Restaurant::facilities()->filtered($wifi)->get();
Run Code Online (Sandbox Code Playgroud)

这不完全是您所需要的,但查询范围可能是您想要用来获取您正在尝试的内容的内容.

关键是要知道关系类可以像查询构建器一样使用 - 例如:

$this->belongsTo('Facility')->where('wifi', '=', $wifi)->orderBy('whatever', 'asc')->get();
Run Code Online (Sandbox Code Playgroud)


Ant*_*iro 1

有一些方法可以过滤两者,这是使用 QueryBuilder:

Restaurant::join('facilities','facilities.restaurant_id','=','restaurants.id')
                ->where('name','bbq')
                ->where('facilities.wifi','!=', 1)
                ->get();
Run Code Online (Sandbox Code Playgroud)