duanchuopi2298 2017-04-17 14:51
浏览 64

访问对象的属性作为laravel中where子句中的键

I'll start directly off with my example. The thing is, I have a couple of hasMany and belongsTo relationships and I'd like to access a property of one of the returned object as a key in a where clause. Let's say I have a model named Price and it has three belongsTo connections to three models named profileSystem, profileType and colorGroup. Each of my three other models have a hasMany connection to the Price model. So if I have an instance of my profileType model, I'd like to call it's price where accordingly the profileSystem and the colorGroup parents will have some certain values. Example that works:

App\ProfileType::find(1) 
                -> prices -> where('profileType', App\ProfileType::find(1))
                -> where('colorGroup', App\ColorGroup::find(1))
                -> first()->value;

As you can see, the comparison here works directly with the whole instances of the colorGroup and profileType models that belong with the Price model. What I'd like to do is no to compare the whole models, but only a single property, like so:

->where('colorGroup->id', 1)

or

->where('colorGroup->id', App\ColorGroup::find(1) -> id)

The question is all syntax that I'm not common with in laravel. I also couldn't find anything in the documentation. Thanks in advance!

  • 写回答

3条回答 默认 最新

  • dqdtgiw4736 2017-04-17 15:15
    关注

    You can use scopes for each of these:

    class ColorGroup {
    
        public function scopeColor($query, $color)
        {
            return $query->where('id', $color);
        }
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题