[英]How can i use related model scope inside whereHas Laravel 8
我有兩個模型。 Task
和任務TaskCheck
在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);
}
}
在Task
model 我有
class Task extends Model
{
public function taskCheck(): HasMany
{
return $this->hasMany(TaskCheck::class)->with(['taskState', 'owner']);
}
}
並想使用這樣的東西:
public function scopeHasOwner(Builder $query, int $taskOwnerId): Builder
{
return $query->whereHas('taskCheck', function ($q) use ($taskOwnerId) {
$q->hasOwner($taskOwnerId);
});
}
但是,這會引發異常Call to undefined method App\Models\Task::hasOwner()
,因為內部查詢似乎不知道任務 model。
我知道我可以改用它並且它有效
public function scopeHasOwner(Builder $query, int $taskOwnerId): Builder
{
return $query->whereHas('taskCheck', function ($q) use ($taskOwnerId) {
$q->where('user_id', '=', $taskOwnerId);
});
}
但我不想在每個相關的 model 中重復 where 子句,因為在關系中存在更多相關模型,它們將使用類似的功能,我只想將它放在一個地方。
在您的TaskCheck
model 中,您擁有ownedBy()
scope,但您在whereHas
查詢中調用了hasOwner()
。
將您的查詢更改為ownedBy()
$query->whereHas('taskCheck', function ($q) use ($taskOwnerId) {
$q->ownedBY($taskOwnerId);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.