laravel查询构建器()何时必须具有多个标签(带有product_tags枢轴表多个对象)
我是Laravel的新手,我有一个复杂的查询要构建。除了用户要求多个标签(tags = 1、2、3
)时,我设法对其进行了排序。显示的产品必须具有用户询问的所有标签
(不仅是一两个,而且全部)。
我在SQL中有查询(此示例是两个标签,我会根据传递数量的标签将其切换到不同的数字):
SELECT m.*
FROM meals m
WHERE EXISTS (
SELECT 1
FROM meals_tags t
WHERE m.id = t.meals_id AND
t.tags_id IN (227,25)
HAVING COUNT(1) = 2
);
一个完美工作,但是在将其转换为雄辩的查询构建器时,我有一个问题。其中
方法。
我有另一个其中方法中包含在同一查询中,因此我也想附加此方法。
我已经尝试过:
DB::table('meals')
->select('id')
->where(function ($query) use ($parameters) {
if (isset($parameters['tags'])) {
$array = explode(',', $parameters['tags']);
$query->select(DB::raw(1))
->from('meals_tags')
->where('meals.id', '=', 'meals_tags.meals_id')
->whereIn('meals_tags.tags_id', $array)
->having(DB::raw('COUNT(1)'), '=', count($parameters['tags']));
}
});
但是我找不到方法。 Laravel和PHP的新手。
假设我有表 和标签
feals_tags
将它们连接起来(许多与许多)。
$ paramaters
是从get> get(...?tags = 1,2,3& lang = en& enother = eN&emp = somets ...)
,它们是键值对(['tags'=>'1,2,3','lang'=>'en']
)
$ parameters ['tags'] 是类型
(正面字符串
带有逗号分隔数字的字符串Integers
大于0
),这样我就可以选择在需要时爆炸。
I am new to Laravel and I got a complicated query to build. I managed to sort it except for when a user asks for multiple tags (tags = 1, 2, 3
). Product shown has to have all tags
that the user asks (not only one or two but all of them).
I have the query in SQL (this example is two tags, I would switch it to different numbers based on how many tags are passed):
SELECT m.*
FROM meals m
WHERE EXISTS (
SELECT 1
FROM meals_tags t
WHERE m.id = t.meals_id AND
t.tags_id IN (227,25)
HAVING COUNT(1) = 2
);
This one works perfectly, but I have an issue when translating it to an Eloquent query builder where
method.
I have another where
method included in the same query so I want to attach this one as well.
I have tried this:
DB::table('meals')
->select('id')
->where(function ($query) use ($parameters) {
if (isset($parameters['tags'])) {
$array = explode(',', $parameters['tags']);
$query->select(DB::raw(1))
->from('meals_tags')
->where('meals.id', '=', 'meals_tags.meals_id')
->whereIn('meals_tags.tags_id', $array)
->having(DB::raw('COUNT(1)'), '=', count($parameters['tags']));
}
});
But I can't find a way. New to Laravel and PHP.
Let's say I have table meals
and tags
with meals_tags
to connect them (many to many).
$paramaters
are comming from GET (...?tags=1,2,3&lang=en&another=something...)
, they are an array of key-value pairs (['tags' => '1,2,3', 'lang' => 'en']
)
$parameters['tags']
is of type string
with comma separated numbers (positive integers
greater than 0
) so that I have the option to explode it if needed somewhere.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设您已经定义了
allatsstomany
(多次 - 多)feal_tags
feal>用餐
模型,您可以尝试Assuming that you have defined
belongsToMany
(Many-to-Many)meal_tags
relationship on theMeal
model, you can try