P
P
Pavel Zhukau2015-08-13 23:13:40
MySQL
Pavel Zhukau, 2015-08-13 23:13:40

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

1 answer(s)
D
D', 2015-08-13
@NikesDark

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');
}

And for the Category model:
public function guides()
{
  return $this->belongsToMany('App\Models\Guide');
}

Now we can simply:
$ids = [1, 2, 3];
$guides = App\Models\Guide::whereHas('categories', function ($q) use ($ids)
{
  return $q->whereIn('id', $ids);
})->get();

Get a list of all guides that are included in categories with ID = 1, 2, 3
Or to get the number of guides in a category:
$category = Category::find(1);
$count = $category->guides()->count();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question