Answer the question
In order to leave comments, you need to log in
How to find a model instance in Laravel by content in the database?
Good night all. Faced one difficulty. There is a Guides model that has id, categories_id fields. And categories_id stores json in the format ["1","2","3"]. And the bottom line is this: I need to find all the rows from the database where the categories_id field json contains the number 1, for example.
Answer the question
In order to leave comments, you need to log in
How ...?
Stop cycling and make normal tables and connections. Hasmany| Many to Many is perfect here (I don’t know how it should work there).
Example:
Guides table: Categories
table:
Link table (category_guide):
Write for the Guide model:
public function categories()
{
return $this->belongsToMany('App\Models\Category');
}
public function guides()
{
return $this->belongsToMany('App\Models\Guide');
}
$ids = [1, 2, 3];
$guides = App\Models\Guide::whereHas('categories', function ($q) use ($ids)
{
return $q->whereIn('id', $ids);
})->get();
$category = Category::find(1);
$count = $category->guides()->count();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question