Database 左联在一个多对多的关系中雄辩

Database 左联在一个多对多的关系中雄辩,database,laravel,eloquent,many-to-many,Database,Laravel,Eloquent,Many To Many,我不应该使用原始查询,它会导致这种混乱!你能帮我改进一下吗 @foreach($attributes as $attribute) {{ Form::bsText($attribute->name, $attribute->title, $customer->attributes()->find($attribute->id)->pivot->value ?? '') }} @endforeach 属性模型: public functi

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

@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'));
}
$attributes = Attribute::all();
$customer = Customer::with('attribues')...
$customer->attributes = $customer->attributes->keyBy('id');
$attributes = Attribute::all();
$customer = Customer::with('attribues')...
第一种选择:

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

控制器:

public function show(Customer $customer)
{
    $attributes = Attribute::all();
    return view('admin.customers.show', compact('customer', 'attributes'));
}
$attributes = Attribute::all();
$customer = Customer::with('attribues')...
$customer->attributes = $customer->attributes->keyBy('id');
$attributes = Attribute::all();
$customer = Customer::with('attribues')...
视图:

第二种选择:

此选项基于“使用集合->属性”而不是“关系->属性”,以减少数据库查询的数量

控制器:

public function show(Customer $customer)
{
    $attributes = Attribute::all();
    return view('admin.customers.show', compact('customer', 'attributes'));
}
$attributes = Attribute::all();
$customer = Customer::with('attribues')...
$customer->attributes = $customer->attributes->keyBy('id');
$attributes = Attribute::all();
$customer = Customer::with('attribues')...
视图:

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

好主意->键盘输入'id',谢谢!