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

Ben*_*nRH 12 php relationship laravel eloquent laravel-4

我有一个模型,它属于另一个模型,该模型属于第三个模型,我想要一个雄辩的方法将第一个模型与第三个模型联系起来.

但是,似乎没有belongsToThrough(或hasOneThrough)方法.我已经尝试过链接多种belongsTo方法,但这没有用(Call to undefined method Illuminate\Database\Query\Builder::belongsTo()).有任何想法吗?

以下是模型的示例:

// 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 {
}
Run Code Online (Sandbox Code Playgroud)

我想做的是在Origin模型中添加如下方法:

// 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');
}
Run Code Online (Sandbox Code Playgroud)

所以我可以使用$originInstance->target->title

Raz*_*zor 16

public function target() { 
    $middle = $this->belongsTo('Middle','middle_id'); 
    return    $middle->getResults()->belongsTo('Target'); 
}
Run Code Online (Sandbox Code Playgroud)


Mla*_*vic 14

如果这是瓶子中的消息,并且瓶子由用户拥有(user > bottle > message)

我知道获取关系对象的唯一方法是:

// THIS IS IN App\Message

public function bottle()
{
    return $this->belongsTo('App\Bottle');
}

public function user()
{
    return $this->bottle->belongsTo('App\User');
}
Run Code Online (Sandbox Code Playgroud)