D
D
Dmitry2019-03-19 10:30:18
MySQL
Dmitry, 2019-03-19 10:30:18

How to make such a request using laravel?

Hello, help me understand.
Made a query to the database using DB::select()
part of the code:

class ProductsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Products::all();
        $categories = DB::table('categories')->get();
        //$categoriesRelationship = DB::table('categories_relationship')->get();
        $categoriesRelationship = DB::select("SELECT
                                            categories.category_filter_by AS 'catFilterBy',
                                            products.id AS 'productID'
                                          FROM
                                            categories, products, categories_relationship
                                          WHERE
                                            categories.category_id = categories_relationship.category_id
                                          AND
                                            products.id = categories_relationship.object_id"
                                        );

        return response()->json([
            'productsList' => $products,
            'categories' => $categories,
            'categoriesRelationship' => $categoriesRelationship,
        ]);
    }
}

getting $categoriesRelationship done right?
Is there any other way to make such a request using laravel methods?
Thanks

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2019-03-19
@dlnsk

DB::table('products')
   ->select(['products.id', 'categories.category_filter_by'])
   ->join('categories_relationship', 'products.id', '=', 'categories_relationship.object_id')
   ->join('categories', 'categories.category_id', '=', 'categories_relationship.category_id')
   ->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question