【发布时间】:2014-06-15 11:08:43
【问题描述】:
我有一个模型,它属于另一个模型,那个模型属于第三个模型,我想要一个雄辩的方法来将第一个模型与第三个模型联系起来。
不过,似乎没有 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等
【问题讨论】:
-
你试过
hasManyThrough吗? -
我没有,我只是假设这是许多关系。让我试试,谢谢!
-
HasOne 和 HasMany 都扩展了抽象的 HasOneOrMany,它们非常相似。我很确定它对你有用,但是它可能会返回一个 Collection 而不是单个模型,这可能是我现在能想到的唯一缺点。
-
啊,不,很遗憾,这行不通。这是因为我的源表属于中间表,中间表属于目标表,而中间表不属于源表,这是
hasManyThrough要求的。让我澄清一下这个问题。 -
好的,那就不行了。目前没有这种方式通过关系的方法,只有
A -> hasOneOrMany -> B -> hasOneOrMany C的另一种方式。但是您仍然可以使用点嵌套关系,例如 origin->middle->target->title (如果到处都是 hasOne)
标签: php laravel laravel-4 relationship eloquent