具有 Laravel 和多对多关系的 Metronic 数据表

Metronic Datatable with Laravel and many-to-many relationship

我有以下问题:

我在客户和分支机构之间建立了多对多关系。这已经过测试并且正在工作。但是现在我不想使用这种关系来显示客户数据中的分支名称table。

我收到这个错误:

"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'branches.name' in 'field list' (SQL: select customers.*, branches.name from customers where customers.deleted_at is null order by id asc limit 50 offset 0)"

我不确定如何 select 正确 table 与客户一起 table。

这是负责调用数据的controller方法table class:

public function fetch(Request $request) {
    Notification::visit(CustomersRetrieved::class);
    return response()->json((new CustomerDatatable($request))->render());
}

这是数据table class:

<?php
/**
 * Created by PhpStorm.
 * User: NEWPC-1
 * Date: 4-1-2019
 * Time: 08:31
 */

namespace Modules\CRM\Datatables;

use App\Support\Datatables\Datatable;
use App\Support\Datatables\DatatableContract;
use Illuminate\Support\Facades\Log;
use Modules\CRM\Models\Customer;

class CustomerDatatable extends Datatable implements DatatableContract
{
    /**
     * @return mixed|string
     */
    public function model()
    {
        return Customer::class;
    }

    /**
     * @return array|mixed
     */
    public function orders()
    {
        return [
            'code' => 'code',
            'name' => 'name',
            'branch' => 'branch',
            'email' => 'email',
            'phone_number' => 'phone_number',
            'postal_code' => 'postal_code',
            'city' => 'city',
            'address' => 'address',
            'address_number' => 'address_number',
        ];
    }

    /**
     * @return mixed
     */
    protected function newQuery()
    {
        $query = parent::newQuery()->with('branches')->select(['customers.*','branches.name']);
        Log::info(json_encode($query));
        if(isset($this->input['query']) && strlen($q = $this->input['query']) > 0) {
            $query->search($q);
        }
        return $query;
    }

    /**
     * @return mixed
     */
    protected function getQueryCount()
    {
        $query = parent::newQuery();

        if(isset($this->input['query']) && strlen($q = $this->input['query']) > 0) {
            $query->search($q);
        }
        return $query->count();
    }

    public function exportable()
    {
        return [
            ['key' => 'name'],
            ['key' => 'branch'],
            ['key' => 'address'],
            ['key' => 'address_number'],
            ['key' => 'postal_code'],
            ['key' => 'city'],
        ];
    }
}

这是对应的javascript:

customer_datatable = customer_element.CustomDataTable({
        rows: {
            beforeTemplate: function (row, data, index) {
                row.on('click', function (e) {
                    if ($(e.target).hasClass('kt-badge--info') || $(e.target).hasClass('la') || $(e.target).hasClass('fa') || $(e.target).hasClass('btn') || $(e.target).hasClass('kt-datatable__cell--center')) {
                    } else {
                        window.open(customer_element.data('route-url') + '/crm/customers/' + data.id, '_blank');
                    }
                });
            },
        },
        detail: {
            title: customer_element.data('text-load_contacts'),
            content: contactsInit,
        },
        columns: [
            {
                field: 'id',
                title: '',
                sortable: false,
                width: 20,
                textAlign: 'center',
            },
            {
                field: 'code',
                width: 75,
                title: customer_element.data('column-code'),
                template: function (row) {
                    return row.code;
                }
            },
            {
                field: 'name',
                title: customer_element.data('column-name'),
                width: 300,
                template: function (row) {
                    return '<a href="' + customer_element.data('route-show').replace('__id__', row.id) + '">' + row.name + '</a>';
                }
            },
    //this is the part causing/part of the problem
            {
                field: 'branch',
                title: customer_element.data('column-branch'),
                width: 300,
                template: function (row) {
                    console.log(row);
                }
            },
            {
                field: 'email',
                title: customer_element.data('column-email'),
                width: 250,
                template: function (row) {
                    if (row.email === '') {
                        return '';
                    }
                    var e = row.email.split(','), r = new Array();

                    $.each(e, function (i, x) {
                        r.push('<a href="mailto:' + $.trim(x) + '" class="kt-badge kt-badge--info  kt-badge--inline kt-badge--pill">' + $.trim(x) + '</a>');
                    });
                    return '<span style="line-height:2rem !important;"  title="E-mail this customer">' + r.join('&nbsp;&nbsp;&nbsp;') + '</span>';
                }
            },
            {
                field: 'phone_number',
                title: customer_element.data('column-phone_number'),
                width: 100,
                template: function (row) {
                    if (row.phone_number.length === 0) {
                        return '';
                    }
                    let number = parsePhoneNumber(row.phone_number);

                    return '<a href="tel:' + phoneUtil.format(number, PNF.E164) + '" class="kt-badge kt-badge--brand  kt-badge--inline kt-badge--pill">' + phoneUtil.format(number, PNF.NATIONAL) + '</a>';
                }
            },
            {
                field: 'postal_code',
                title: customer_element.data('column-postal_code'),
                width: 100,
                template: function (row) {
                    return row.postal_code;
                }
            },
            {
                field: 'city',
                title: customer_element.data('column-city'),
                width: 100,
                template: function (row) {
                    return row.city;
                }
            },
        ],
    });

这就是我最终解决它的方法,感谢 Ali Alghozali 和这个 post: MySQL join many to many single row

protected function newQuery()
    {
        $query = parent::newQuery()
                ->leftJoin('branch_customers', 'customers.id', '=', 'branch_customers.customer_id')
                ->leftJoin('branches', 'branches.id', '=', 'branch_customers.branch_id')
                ->select(['customers.*','branches.name as branch']);
        Log::info(json_encode($query));
        if(isset($this->input['query']) && strlen($q = $this->input['query']) > 0) {
            $query->search($q);
        }
        return $query;
    }

您不能在 with 表中 select 列。您需要改用 joinleftJoin