dimanche 25 avril 2021

Laravel DB facade nested array for relatioships

I work with huge database, with many tables, so I prefered working with DB facade instead of Eloquent models.

I have two tables with one-to-many relationship (although foreign key is not declared):

                     +-------------+
+-----------+        | orders      |
| clients   |        +-------------+
+-----------+        | order_id    |
| client_id |<-------| client_id   |
| name      |        | details     | 
+-----------+        +-------------+

I would like to achieve the same result as I would do using with() function:

[
   [
      'client_id' => 1,
      'name' => 'Alfonso',
      'orders' => [
         [
            'order_id' => 32,
            'details' => 'Loren Ipsum'
         ],
         [
            'order_id' => 34,
            'details' => 'Loren Ipsum'
         ]
      ]
   ],
   [
      'client_id' => 2,
      'name' => 'Beatriz',
      'orders' => [
         [
            'order_id' => 15,
            'details' => 'Loren Ipsum',
         ],
         [
            'order_id' => 19,
            'details' => 'Loren Ipsum',
         ],
      ]
   ]
];

I can do it with simple foreach function, I wonder whether there is some way to use something similar to with() function although I don't use models.

The basic query looks like this:

$res = DB::table('clientes')
    ->leftJoin('orders', 'orders.client_id', '=', 'cliends.client_id')
    ->get()->toArray();


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/3xnyelZ
via IFTTT

Aucun commentaire:

Enregistrer un commentaire