Laravel Livewire 组件偏移

Posted

技术标签:

【中文标题】Laravel Livewire 组件偏移【英文标题】:Laravel Livewire component offset 【发布时间】:2020-06-16 18:10:50 【问题描述】:

我正在尝试通过在 Livewirecomponent 内部调用的 laravel 控制器获取一些技术人员数据。在某些情况下,控制器会返回null,因为没有相关的技术人员。

这是我渲染视图的 livewire 组件:

class TechniciansAssociated extends Component

    public function render()
    
        $technicians = (new HomeController())->getTechnicians();

        return view('livewire.dashboard.technicians-associated', [
            'technicians' => $technicians,
        ]);
    

从家庭控制器调用的这里函数:

public function getTechnicians()

    $customer_ids = json_decode(User::find(Auth::id())->userCustomers->customer_id,true);

    $technicians_data = DB::connection('mysql')
        -> select('SELECT distinct users.id, users.name, users.surname, users.lastname, users.email, users.cargo, users.photo
           FROM users
           INNER JOIN contractsproductsmulti AS cpm ON users.id = cpm.userId
           INNER JOIN contractsproducts AS cp ON cp.id = cpm.contractproduct_id
           INNER JOIN contracts AS cont ON cont.id = cp.idcontract
           WHERE users.isActive = 1 AND cont.idCustomer IN (?)', $customer_ids
        );

    if (count($technicians_data) > 0)
        return $technicians_data;
    

    return null;

最后,当尝试获取渲染 livewire 视图的主视图时,我遇到了错误

@section('content')

<section id="dash-cust-info">
    <div class="row p-t-30 p-b-30">
        <div class="col-md-6">
            <h4>Customer info</h4>
        </div>
        <div class="col-md-3">
            <h4>Comm_1</h4>
            <div class="card no-border no-margin">
                @livewire('dashboard.commercials-associated')
            </div>
        </div>
        <div class="col-md-3">
            <h4>Comm_2</h4>
            <div class="card no-border no-margin">
                @livewire('dashboard.technicians-associated')
            </div>
        </div>
    </div>
....

错误:

Undefined offset: 1 (View: /......../resources/views/home.blade.php)

【问题讨论】:

【参考方案1】:

我猜 this answer 为 livewire 中的此类问题提供了很好的解释。把它留在这里,以便将来遇到此类问题的任何人都能得到帮助。不客气

【讨论】:

【参考方案2】:

好的,LiveWire 组件需要一个 html 元素才能在它自己的视图上获得结果。例如:

<div> //missed on my code
    @foreach($users as $user)
        $user->id
    @endforeach
</div>

【讨论】:

以上是关于Laravel Livewire 组件偏移的主要内容,如果未能解决你的问题,请参考以下文章

laravel - livewire 整页组件

Laravel 和 Livewire:组件更改时如何执行 javascript 函数?

在 Laravel 8 Jetstream 的 Blade 组件中绑定 Livewire 属性

Laravel(Livewire)中的组件拆分和保留参数

Laravel Livewire:组件还是控制器? [关闭]

Laravel Livewire - 如何强制子组件刷新