R
R
ralo2017-10-15 13:41:32
MySQL
ralo, 2017-10-15 13:41:32

Eloquent ORM unable to compose query?

There are two tables in one where bags are stored and all the information on them in the other is stored photos of these bags,
here they are ,
59e33a06137eb323767494.png59e33a0b8a70e098180525.png
my query looks like this
$data = DB::table('bags')->leftJoin('bags_photo', 'bags.id' , '=', 'bags_photo.bag_id')->get()->toArray();
$array = json_decode(json_encode($data), true);
how to change my request so that I get all its photos and information about it for each bag,
because I now have duplicate information on bags depending on the number of photos for the bag and it turns out something like this
59e33b258f891831450868.png
59e33b2e7b587616373693.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene Wolf, 2017-10-15
@ralo

For this, in Eloquent (and not only) there are connections, in your case - one to many , i.e. one bag -> many photos.
PS Eloquent is such a very handy thing built into Laravel for working with data from the database, incl. allows you to quickly set up links between objects.
----------
There is also an option to do it right at the SQL query level, for MySQL it will look something like this:

SELECT service_category.*, GROUP_CONCAT(service.id SEPARATOR ',') AS ids
FROM service_category 
LEFT JOIN service ON service.category_id = service_category.id
GROUP BY service_category.id

In this example, the service table refers to the service_category table via the service.category_id field. As a result, we get the following additional column, which lists all "services" for the current category (their IDs) separated by commas:
UPD. The query you have in the example is NOT Eloquent , it's QueryBuilder .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question