gpt4 book ai didi

database - 与模型属性的 where 条件的 Eloquent 关系

转载 作者:太空狗 更新时间:2023-10-30 01:57:43 26 4
gpt4 key购买 nike

我有两个模型 StudentStudentRevision,其中 Student 模型与 StudentRevision< 有 hasMany 关系模型。我在 Student 中定义了一个 hasMany 关系

public function revisions()
{
return $this->hasMany(
'StudentRevision',
'sid'
);
}

我在 students 表(学生模型)中有一个字段,它引用了 student_revisions 表中学生的当前版本。

表结构是这样的。

学生 sid srid name ....

student_revisions srid sid batch ....

现在我想定义 hasOneStudentRevision 模型的关系,该模型引用与 Student 链接的 current revision。目前我将这种关系定义为:

public function current()
{
return $this->hasOne(
'StudentRevision',
'sid'
)
->where('srid', $this->srid);
}

但这种关系的问题是,$this->srid 在查询构建过程中不可用,只有在实际模型可用后才能存在。

请帮助解决这个问题。

最佳答案

我认为您不能将其定义为关系。但你可以做的是:

public function current(){
return $this->revisions()->where('srid', $this->srid)->get();
}

这样你就可以通过$student->current()访问它。您甚至可以走得更远,让它变得更关系,例如:

public function current(){
return $this->revisions()->where('srid', $this->srid);
}

public function getCurrent(){
return $this->current()->get();
}

protected $appends = array('current');

这里我们为我们的属性定义了一个访问器。 Laravel Docs (向下滚动到底部)

然后我们可以像这样使用它:

$student->current; // retrieves the model
$student->current(); // retrieves an instance of the query builder

关于database - 与模型属性的 where 条件的 Eloquent 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27381351/

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