2

I have a table called recipes that has a field cast to an array that houses ids from another table ingredients. A user can select from a form, specific ingredients they want to see recipes for.

Is there a way I can take the submitted list of ids and only pull recipes that have some of those ids? I say some because I don't want to limit to recipes that have only ALL of the ids. Meaning if someone chooses chicken, onions, and celery and there are recipes that contain those ingredients plus carrots, peppers and mushrooms I want to show those as well.

The only query I can come up with seems to compare exact to exact.

$recipes = Recipes::whereIn('ingredient_ids', $request->ingredient_ids)->get();

With ingredient_ids being the list of submitted ingredients.

4

1 回答 1

0

我知道您将该字段转换为 an array,但这可能有效:如果您的数据库是 MySQL 或 PostgreSQL,您可以使用whereJsonContains()method

从文档:

MySQL 和 PostgreSQL 支持whereJsonContains多个值:

$users = DB::table('users')
            ->whereJsonContains('options->languages', ['en', 'de'])
            ->get();

所以在你的代码中试试这个:

$recipes = Recipes
       ::whereJsonContains('ingredient_ids', $request->ingredient_ids)
       ->get();
于 2019-09-07T18:40:20.077 回答