duanjia8215 2014-04-29 13:21
浏览 98

Laravel hasManyThrough等价物:通过另一个模型的belongsTo关系

I've got a model, it belongs to another model, that model belongs to a third model, and I want an eloquent method to relate the first model to the third one.

There doesn't appear to be a belongsToThrough (or hasOneThrough) method, though. I've already tried chaining multiple belongsTo methods, but that hasn't worked (Call to undefined method Illuminate\Database\Query\Builder::belongsTo()). Any ideas?

Here is an example of the models:

// The first model
// Schema: this model has a middle_id column in the database
class Origin extends Eloquent {
    public function middle()
    {
        return $this->belongsTo('Middle');
    }
}

// The second model
// Schema: this model has a target_id column in the database, but NOT an origin_id column
class Middle extends Eloquent {
    public function target()
    {
        return $this->belongsTo('Target');
    }
}

// The third model
class Target extends Eloquent {
}

What I'd like to do is add something like the following method to the Origin model:

// A relationship method on the first "origin" model
public function target()
{
    // First argument is the target model, second argument is the middle "through" model, third argument is the database column in middle model that it uses to find the target model, or soemthing
    return $this->hasOneThrough('Target', 'Middle', 'target_id');
}

So that I can use $originInstance->target->title, etc.

  • 写回答

3条回答 默认 最新

  • doutangtan6386 2014-04-30 22:58
    关注
    public function target() { 
        $middle = $this->belongsTo('Middle','middle_id'); 
        return    $middle->getResults()->belongsTo('Target'); 
    }
    
    评论

报告相同问题?

悬赏问题

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