Laravel 4-如何使用关系列所在的条件 [英] Laravel 4 - How to use where conditions for relation's column
问题描述
这就是我想要的,我有两个表.一个是餐厅",另一个是设施".
This is what I want, I have two tables. one is 'Restaurants' and other is 'Facilities'.
这些表很简单..和一对一关系.例如,有一个餐厅表,其中包含id
,name
,slug
等,而另一个名为facilities
的表具有id
,restaurant_id
,wifi
,parking
等
The tables are simple.. and One-To-One relations. like there is a restaurant table with id
, name
, slug
, etc and another table called facilities
with id
, restaurant_id
, wifi
, parking
, etc
这是我的模特:
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');
}
}
我想这样做Select * from restaurants r left join facilities rf on r.id=rf.restaurant_id where r.name = 'bbq' and rf.wifi != '1'
.
如何使用Eloquent做到这一点?
How to use Eloquent to do that?
ps.很抱歉从 https://stackoverflow进行修改. com/questions/14621943/laravel-how-to-to-use-where-conditions-for-relations-column# = ,但我也遇到类似的问题.
ps. sorry for modify from https://stackoverflow.com/questions/14621943/laravel-how-to-use-where-conditions-for-relations-column#= , but I have the similar problem.
推荐答案
您可以在关系对象上使用where
和其他基于sql的方法.
You can use where
and other sql-based methods on the relationship objects.
这意味着您可以在模型中创建自定义方法:
That means you can either create a custom method in your model:
class Restaurant extends Eloquent {
protected $table = 'restaurants';
public function facilities($wifi) {
return $this->belongsTo('Facility')->where('wifi', '=', $wifi);
}
}
或者您可以尝试使用查询范围:
class Restaurant extends Eloquent {
protected $table = 'restaurants';
public function facility() {
return $this->belongsTo('Restaurant');
}
public function scopeFiltered($query, $wifi)
{
return $query->where('wifi', '>', 100);
}
}
然后:
$wifi = 1;
$restaurants = Restaurant::facilities()->filtered($wifi)->get();
这可能并不是您真正需要的,但是查询范围很可能是您想要用来获取所要尝试内容的范围.
This isn't exactly what you need likely, but query scopes is likely what you want to use to get what you're attempting.
关键是要知道关系类可以像查询构建器一样使用-例如:
THe key point is to know that relationship classes can be used like query builders - for example:
$this->belongsTo('Facility')->where('wifi', '=', $wifi)->orderBy('whatever', 'asc')->get();
这篇关于Laravel 4-如何使用关系列所在的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!