Laravel-查询构建器-左联接多态关系,仅不同

Kin*_*ley 5 php laravel vue.js laravel-query-builder laravel-5.3

因此,我使用Vue 2.0和Laravel 5.3创建应用程序。

我已经使用Laravel提供的内置分页功能,通过Vue实现了自己的可排序表。

一切工作正常-除了,我试图离开加入“媒体”多态表,以便可以在表中显示图像。

要启用排序,我不得不使用查询生成器,因为您不能使用Eloquent(AFAIK)对关系进行排序。

我的关系定义如下:

$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');
Run Code Online (Sandbox Code Playgroud)

哪个工作很棒。但是,在不重复(复制)任何行的情况下,我如何精确地加入多态关系?

我有这个:

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

哪个显示媒体(如果它在多态表中有关系)。但是,例如,如果我有1个特定库存物品的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
    "));
Run Code Online (Sandbox Code Playgroud)

我想我需要使用groupBy,但是我不确定在哪里定义它。如果我做

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

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

有没有人遇到过类似情况或知道将我的组放在哪里以显示1 /不同的库存项目?

编辑:

我可以使用以下方法修复:

$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');
});
Run Code Online (Sandbox Code Playgroud)

然后设置strict => false我的database.php

Gay*_*yan 4

正如错误所述,当name列不在GROUP BY子句中时,就会出现此问题。

为了解决这个变化

'strict' => true, 
Run Code Online (Sandbox Code Playgroud)

在您的文件mysql下的配置中connectionsconfig/database.php

'strict' => false,
Run Code Online (Sandbox Code Playgroud)

此外,我强烈鼓励使用多态关系而不是左连接和雄辩。