[英]How can i use related model scope inside whereHas Laravel 8
I have two models.我有两个模型。
Task
and TaskCheck
Task
和任务TaskCheck
in TaskCheck
i have在
TaskCheck
我有
class TaskCheck extends Model
{
public function task(): BelongsTo
{
return $this->belongsTo(Task::class);
}
public function owner(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function scopeOwnedBy(Builder $query, int $userId): Builder
{
return $query->where('user_id', '=', $userId);
}
}
in Task
model i have在
Task
model 我有
class Task extends Model
{
public function taskCheck(): HasMany
{
return $this->hasMany(TaskCheck::class)->with(['taskState', 'owner']);
}
}
And would like to use something like this:并想使用这样的东西:
public function scopeHasOwner(Builder $query, int $taskOwnerId): Builder
{
return $query->whereHas('taskCheck', function ($q) use ($taskOwnerId) {
$q->hasOwner($taskOwnerId);
});
}
however this throws exception Call to undefined method App\Models\Task::hasOwner()
as it seems inner query is not aware of Task model.但是,这会引发异常
Call to undefined method App\Models\Task::hasOwner()
,因为内部查询似乎不知道任务 model。
I know I could use this instead and it works我知道我可以改用它并且它有效
public function scopeHasOwner(Builder $query, int $taskOwnerId): Builder
{
return $query->whereHas('taskCheck', function ($q) use ($taskOwnerId) {
$q->where('user_id', '=', $taskOwnerId);
});
}
but i would rather not repeat the where clause in every related model, because there are more related models deeper in relationships which would use similar functionality and i would like to have it on one place only.但我不想在每个相关的 model 中重复 where 子句,因为在关系中存在更多相关模型,它们将使用类似的功能,我只想将它放在一个地方。
In your TaskCheck
model, you have ownedBy()
scope, but you called hasOwner()
in the whereHas
query.在您的
TaskCheck
model 中,您拥有ownedBy()
scope,但您在whereHas
查询中调用了hasOwner()
。
Change your query to ownedBy()
将您的查询更改为
ownedBy()
$query->whereHas('taskCheck', function ($q) use ($taskOwnerId) {
$q->ownedBY($taskOwnerId);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.