B
B
BonBon Slick2017-03-23 21:59:04
MySQL
BonBon Slick, 2017-03-23 21:59:04

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();

How to connect posts table and filter by post_title?
2 - Return posts, in the name of which and the name of which categories (that is, there is a post, it belongs to the category, and the name of the category is in question) contains the search text. The user entered for example "category", it displays posts with the name "category" and posts whose categories have the name "category".
$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();
// вернет только посты

It will return only the table that has been joined.
$query = DB::table('posts')->join('some_pivot_table', 'posts.id', '=', 'some_pivot_table.post_id')->get()

I'm sitting practicing the Laravel 5.4 QueryBuilder manual, a lot is missing here, as if torn out in pieces, nothing is clear. I don't understand how it works.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kulik, 2017-03-23
@BonBonSlick

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();

Without models if
1)
DB::table('posts')
    ->select('posts.*')
    ->where('user_id', $userID)
    ->join('user_watchlist', 'user_watchlist.post_id', '=', 'posts.id')
    ->orderBy('posts.title', 'DESC')
    ->get();

2)
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 question

Ask a Question

731 491 924 answers to any question