dongxibo2095 2019-01-14 21:18
浏览 33

Laravel Eloquent为中间关系添加过滤器以获得更深层次的关系

I have a table (Model3) that I am trying to query based on Model1 and Model2 relationships and a filter involved. I am trying to query all Model3 records given some Model1.id and Model2.status=0.

Model1    Model2         Model3  
PK: id    PK: id         PK: id
          FK: model1_id
          FK: model3_id
          status

Model1 can have many Model2s. A Model2 has a FK to a single Model3. Model3 is not related to Model2. I thought its (less) complicated to do this in two steps. So I defined a relation on Model1:

class Model1 {
    ...
    public function Model2s() {  
        return $this->hasMany('Model2', 'model1_id')
                    ->where('status', '=', '0' );
    }
}

Then I would have to loop through the Model2 results and then get at the related Model3. So I created a relation on Model2 (half of a one-to-one relationship):

class Model2 {
    ...
    public function Model3() {
        return $this->belongsTo('Model3', 'model3_id' );
    }        
}

The problem being that Model2 can have 1000's of records to loop through to get it's Model3, which will be time consuming.

Is there a way to do this with a hasManyThrough relation on Model1 that takes into account I need a filter of Model2.status = 0? Then I can maybe use a single query to get at Model3?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
    • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
    • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
    • ¥15 手机接入宽带网线,如何释放宽带全部速度
    • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测