gpt4 book ai didi

php - Laravel hasManyThrough 等效 : belongsTo relationship through another model

转载 作者:行者123 更新时间:2023-12-03 00:35:04 26 4
gpt4 key购买 nike

我有一个模型,它属于另一个模型,该模型属于第三个模型,我想要一种 Eloquent 方法将第一个模型与第三个模型关联起来。

不过,似乎没有belongsToThrough(或hasOneThrough)方法。我已经尝试过链接多个 belongsTo 方法,但这并没有奏效(调用未定义的方法 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

最佳答案

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

更新:

从 laravel 5.8 开始,您可以使用 hasOneThrough关系:

public function target() { 
return $this->hasOneThrough('Target', 'Middle');
}

关于php - Laravel hasManyThrough 等效 : belongsTo relationship through another model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23365905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com