【问题标题】:Left Join in a many to many relation in Eloquent左加入 Eloquent 中的多对多关系
【发布时间】:2019-04-21 11:45:34
【问题描述】:

我不应该使用原始查询,这会导致混乱!你能帮我改进一下吗?

@foreach($attributes as $attribute)
        {{ Form::bsText($attribute->name, $attribute->title, $customer->attributes()->find($attribute->id)->pivot->value ?? '') }}
@endforeach

属性模型:

public function customers()
{
    return $this->belongsToMany(Customer::class);
}

客户模型:

public function attributes()
{
    return $this->belongsToMany(Attribute::class)->withPivot('value');
}

控制器:

public function show(Customer $customer)
{
    $attributes = Attribute::all();
    return view('admin.customers.show', compact('customer', 'attributes'));
}

【问题讨论】:

    标签: database laravel eloquent many-to-many


    【解决方案1】:

    第一个选项:

    您可以将客户属性集合的索引重新设置为属性id,并通过id访问客户属性集合中的模型。

    控制器:

    $attributes = Attribute::all();
    $customer = Customer::with('attribues')...
    $customer->attributes = $customer->attributes->keyBy('id');
    

    查看:

    @foreach($attributes as $attribute)
            {{ Form::bsText($attribute->name, $attribute->title, $customer->attributes[$attribute->id]->pivot->value ?? '') }}
    @endforeach
    

    第二个选项:

    此选项基于使用集合 ->attributes 而不是关系 ->attributes() 以减少数据库查询的计数。

    控制器:

    $attributes = Attribute::all();
    $customer = Customer::with('attribues')...
    

    查看:

    @foreach($attributes as $attribute)
            {{ Form::bsText($attribute->name, $attribute->title, $customer->attributes->where('id', $attribute->id)->first()->pivot->value ?? '') }}
    @endforeach
    

    第一个选项应该比第二个更快。

    【讨论】:

    • 好主意->keyBy('id'),谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-06-13
    • 2021-10-09
    • 1970-01-01
    • 2019-03-26
    • 2013-05-15
    • 2014-09-27
    • 1970-01-01
    • 2017-04-20
    相关资源
    最近更新 更多