dongtui6347 2015-10-09 07:42
浏览 107
已采纳

Laravel - 模型修改

I need to refactor project and I have problem. Below is old, working model, where 'active' column is in "people" table. I need to move 'active' column into "people_translations" table. Do you have any Idea to modify scopeActive method? Thanks a lot!

Old working model:

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';
}

Old tables structure:

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


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

Old query:

$peoples = \People::active()->get();

New tables structure:

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

Table: peoples_translations

id | people_id | language_id | name | active
--------------------------------------------
1 |          7 |          1  | Ann  |      1
  • 写回答

1条回答 默认 最新

  • dsfds2353 2015-10-09 07:52
    关注

    Create a relation for translations inside People Model

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

    Create active scope in People model

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

    It will make subquery for this table and as a result it will get where (count of translations with active = 1) > 0.

    If you have one-to-one relation - look for hasOne relation method instead of hasMany.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥15 如何修改pca中的feature函数
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况