2014-10-28 53 views
0

我在我的组列表显示中使用范围查询,并且组属于国家/地区表。我可以使用组名作为搜索和排序顺序没有任何问题。使用Laravel在不同表中查询范围4

想我想现在要做的有以下几种:存储在Country表

1)搜索国名

存储在Country表2)排序国家名称

# Group Model # 
class Group extends Eloquent 
{ 
    protected $table = 'group'; 
    protected $guarded = array('id'); 

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

    public function scopeName($query, $name) 
    { 
     return $query->where('group_name', 'LIKE', "%$name%"); 
    } 

    public function scopeSortName($query, $order_by = 'asc') 
    { 
     return $query->orderBy('group_name', $order_by); 
    } 
} 

# Country Model # 
class Country extends Eloquent 
{ 
    protected $table = 'country'; 

    public function groups() { 
     return $this->hasMany('group'); 

    } 
} 

# Group Controller # 
public function index() 
{ 
    // search group name 
    $groups = Group::name($s_name); 

    // order group name 
    $groups = $groups->sortName($orderBy); 

} 

回答

0

我不认为有一种方法可以在不加入它的情况下使用其他列表的表格对记录进行排序。因此在我的控制器中我使用了JOIN查询。

# Group Controller # 
public function index() 
{ 
    // join the table Group and Country tables 
    $groups = Group::join('country', 'country.id', '=', 'group.country_id'); 

    // search group name 
    $groups = $groups->name($s_name); 

    // order group name 
    $groups = $groups->sortName($orderBy); 

}