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

时间:2014-04-29 13:21:16

标签: php laravel laravel-4 relationship eloquent

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

但它似乎不是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 {
}

我想要做的是在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');
}

这样我就可以使用$originInstance->target->title

4 个答案:

答案 0 :(得分:16)

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

答案 1 :(得分: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');
}

答案 2 :(得分:1)

您可以使用hasOneThrough,但需要自定义键。

public function parent()
{
    return $this->hasOneThrough(Parent::class, Middle::class, 'id', 'id', 'middle_id', 'parent_id');
}

起源属于Middle,而Middle属于Parent。中间需求具有parent_id外键,原始需求具有middle_id外键。

最后您可以使用:

Origin::find(1)->parent;

答案 3 :(得分:0)

// First Model
public function secondModelRelation()
{
    return $this->belongsTo('App\Models\SecondModel');
}

public function thirdModelRelation()
{
    // Call the thirdModelRelation method found in the Second Model
    return $this->secondModelRelation->thirdModelRelation;
}


// Second Model
public function thirdModelRelation()
{
    return $this->belongsTo('App\Models\ThirdModel');
}


// Third Model