2015-10-09 66 views
1

我需要重构项目,我有问题。以下是旧的工作模式,其中“活跃”列在“人员”表中。我需要将“活动”列移动到“people_translations”表中。 你有任何想法来修改scopeActive方法吗? 非常感谢!Laravel - 模型修改

旧的工作模式:

class BaseModel extends Eloquent 
{ 
    public function scopeActive($query) 
    { 
     return $query->where($this->table . '.active', '=', 1); 
    }  
} 

class People extends BaseModel 
{ 
    protected $table = 'peoples'; 
    protected $translationModel = 'PeopleTranslation'; 
} 

class PeopleTranslation extends Eloquent 
{ 
    public $timestamps = false; 
    protected $table = 'peoples_translations'; 
} 

旧表结构:

Table: peoples 
id | type | date | active 
------------------------- 
7 | .... | ... | 1 


Table: peoples_translations 
id | people_id | language_id | name 
----------------------------------- 
1 |   7 |   1 | Ann 

旧的查询:

$人民= \人::激活() - >获得();

新表结构:

Table: peoples 
id | type | date 
---------------- 
7 | .... | ... 

表:peoples_translations

id | people_id | language_id | name | active 
-------------------------------------------- 
1 |   7 |   1 | Ann |  1 
+0

我不明白你为什么需要额外的表格。 “人民”和“人民通讯”是什么关系? hasOne?有很多? – Tim

+0

Tim,很多语言都有很多language_id,所以有很多 – Paul

回答

1

创建翻译关系的人模型中

public function translations() 
{ 
    return $this->hasMany('PeopleTranslation', 'people_id'); 
} 

在人们模型创建活动的范围

public function scopeActive($query) 
{ 
    return $query->whereHas('translations', function($query) { 
     $query->where('active', 1); 
    }); 
} 

这将使子查询该表,因此它会得到其中(与翻译的计数有效= 1)> 0

如果你有一个一对一的关系 - 寻找hasOne关系法而不是hasMany。

+0

谢谢你的帮助Silwerclaw :) – Paul