Laravel - query builder - left polymorphic relationship pooling, great

Therefore, I use Vue 2.0 and Laravel 5.3 to build the application.

I implemented my own sorting table with Vue using the built-in pagination provided by Laravel.

Everything works fine - besides, I'm trying to go to the polymorphic table "media", so I can show the image in my table.

To enable sorting, I had to use the query builder, since you cannot sort relationships using Eloquent (AFAIK).

I define my relationship as:

$inventories = $inventories->leftjoin('users as inventory_user', 'inventories.user_id', '=', 'inventory_user.id');
$inventories = $inventories->leftjoin('categories as category', 'inventories.category_id', '=', 'category.id');
$inventories = $inventories->leftjoin('inventories as parent', 'inventories.parent_id', '=', 'parent.id');

What a great job. However, how exactly did I leave the polymorphic relation join without repeating (duplicating) any of the lines?

I have it:

$inventories = $inventories->leftJoin('media', function($q) {
    $q->on('media.model_id', '=', 'inventories.id');
    $q->where('media.model_type', '=', 'App\Models\Inventory');
});

( ). , , , 5 () , , , 5 .

:

    $inventories = $inventories->select(DB::raw("
            inventories.id as inventory_id,
            inventories.name as inventory_name,
            inventories.order_column as inventory_order_column,
            category.id as category_id,
            category.name as category_name,
            parent.name as parent_name,
            parent.id as parent_id,
            inventories.updated_at as inventory_updated_at,
            media.name
    "));

, groupBy, , .

$inventories = $inventories->groupBy('inventories.id');

SQLSTATE[42000]: Syntax error or access violation: 1055 'test.inventories.name' isn't in GROUP BY...

- , By, 1/ ?

EDIT:

, :

$inventories = $inventories->leftJoin('media', function($q) {
    $q->on('media.model_id', '=', 'inventories.id');
    $q->where('media.model_type', '=', 'App\Models\Inventory');
    $q->orderBy('media.order_column', 'asc');
    $q->groupBy('model.model_id');
});

strict => false database.php.

+4
2

, , name GROUP BY.

'strict' => true, 

mysql connections config/database.php

'strict' => false,

, .

+1

, :

$categories = $categories->select(DB::raw("
        inventories.id as inventory_id,
        inventories.name as inventory_name,
        inventories.order_column as inventory_order_column,
        category.id as category_id,
        category.name as category_name,
        parent.name as parent_name,
        parent.id as parent_id,
        inventories.updated_at as inventory_updated_at,
        media.name
"))->groupBy('inventories.id');
+1

Source: https://habr.com/ru/post/1665918/


All Articles