gpt4 book ai didi

php - laravel 查询多对多

转载 作者:行者123 更新时间:2023-11-29 07:16:34 25 4
gpt4 key购买 nike

我有 2 个模型,ServiceCategory。它们与这样的多对多关系相关:

Service.php

public function categories()
{
return $this->belongsToMany('App\Category')->withTimestamps();
}
Category.php

public function services()
{
return $this->belongsToMany('App\Service')->withTimestamps();
}

当然,它们由数据透视表连接:

category_service

- category_id
- service_id
- created_at
- updated_at

我想使用本地范围根据类别 ID 过滤服务结果。我做了以下事情:

Service.php

public function scopeFilter($query, $category_ids)
{
$services = Service::whereHas('categories', function (Builder $query) use ($category_ids) {
$query->whereIn('category_id', $category_ids)->get();
});

return $services;
}

但是我遇到了一个Column not found错误,特别是:

Column not found: 1054 Unknown column 'services.id' in 'where clause' (SQL: select * from `categories` inner join `category_service` on `categories`.`id` = `category_service`.`category_id` where `services`.`id` = `category_service`.`service_id` and `category_id` in (1, 2))

1 和 2 是我传递的类别 ID。

我根据找到的答案编写了函数 herehere .

有什么建议吗?

最佳答案

您的错误消息显示您的查询以 categories 开头并且没有加入 services

所以将 ->get() 放在闭包之外。

public function scopeFilter($query, $category_ids)
{
$services = Service::whereHas('categories', function (Builder $query) use ($category_ids) {
$query->whereIn('category_id', $category_ids);
})->get();

return $services;
}

关于php - laravel 查询多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58966293/

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