使用Laravel 4在不同的表中查询范围

时间:2014-10-28 03:24:30

标签: laravel-4

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

我现在想要做的是以下内容:

1)搜索存储在国家/地区表中的国家/地区名称

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);

}

1 个答案:

答案 0 :(得分: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);

}