R
R
Ruslan Safronov2018-07-23 12:15:53
Laravel
Ruslan Safronov, 2018-07-23 12:15:53

How to make a query to the database Laravel 5.6.?

Let's say I have a "News" table, a "categories" table and an intermediate "News categories" table.
How can I make a query to get all the news for one specific category.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mShpakov, 2018-07-23
@mShpakov

Set up relationships and do $category->news
More details here
https://laravel.com/docs/5.6/eloquent-relationship...

K
Kairat Ubukulov, 2018-08-15
@ubukulov

Таблица Новости примерно так. news(id, title, ...)
Таблица Категории categories(id, title)
Таблица category_news(id, category_id, news_id)

В модели Category пишешь метод news

public function news(){
      $news_ids =  $this->hasMany("\App\CategoryNews", "category_id", "id"); // тут получаешь ид всех новостей с таблицы category_news
      $ids = "";
      foreach($news_ids as $item){
            $ids .= $item->news_id . ",";
      }
      $ids = rtrim($ids, ",");
      $news = DB::select("SELECT * FROM news WHERE id IN($ids)");
      return $news;
      
}

как-то так. Попробуйте!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question