Answer the question
In order to leave comments, you need to log in
Complex Laravel SQL queries?
I'm very bad with joins, so I've been hustling on the spot for more than an hour.
1 - we have an intermediate table, in it user_id | post_id .
DB::table('user_watchlist')
->where('user_id', $userID)
->where('user_id', $postD)
// тут надо как-то заджойнить таблицу постов и тсортировать весь результат по тайтлу поста
// ->orderBy('post_title', 'DESC')
->get();
$results = DB::table('categories')
->select('categories.*')
->join('posts', 'posts.categories_id', '=', 'categories.id')
->where('posts.title', 'like', '%' . $searchText . '%')
->orWhere('categories.title', 'like', '%' . $searchText . '%')
//->orderBy( 'DESC') // и как тут отсортировать?
->get();
// вернет только посты
$query = DB::table('posts')->join('some_pivot_table', 'posts.id', '=', 'some_pivot_table.post_id')->get()
Answer the question
In order to leave comments, you need to log in
Create models with the desired relationships. Then
1)
2)
Post::query()->where('title', 'like', "%{$searchText}%")
->orWhereHas('category', function (Builder $query) use ($searchText) {
$query->where('title', 'like', "%{$searchText}%"); // Это относится к таблице с категориями
})
->orderBy('title', 'DESC')
->get();
DB::table('posts')
->select('posts.*')
->where('user_id', $userID)
->join('user_watchlist', 'user_watchlist.post_id', '=', 'posts.id')
->orderBy('posts.title', 'DESC')
->get();
DB::table('posts')
->select('posts.*')
->join('categories', 'posts.categories_id', '=', 'categories.id')
->where('posts.title', 'like', '%' . $searchText . '%')
->orWhere('categories.title', 'like', '%' . $searchText . '%')
->orderBy('posts.title', 'DESC')
->get();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question