laravel - Laravel 多重同步
问题描述
在我的项目中,我有三个用于 eloquent 的表,但我不知道如何相互连接。
第一表:汽车 第二表:汽车属性类别 第三表:汽车属性
机制是,
汽车属性类别有许多汽车属性。这里没有问题。
但是汽车表有汽车属性类别和汽车属性。因此,当我尝试对 Car 属性类别和属性进行雄辩时,我遇到了同步错误。
我尝试了多对多但不能完全成功。
我为 car_id、car_property_category_id 和 property_id 创建了另一个表。但是在表单提交的视图中,汽车属性类别和属性将作为数组传递给控制器。所以我想将它们同步为类别和属性。如下图所示,当属性检查属性类别必须添加到具有属性名称的表中时
我的代码如下;
汽车模型:
public function properties()
{
return $this->belongsToMany(CarProperty::class,'car_car_properties');
}
汽车属性模型
public function category()
{
return $this->belongsTo('App\CarPropertyCategory','category_id','id');
}
public function car()
{
return $this->belongsToMany(Car::class, 'car_car_properties');
}
汽车属性类别模型
public function ozellikleri(){
return $this->hasMany('App\CarProperty','category_id','id');
}
我的刀片文件
@if($propertycategories->count())
@foreach($propertycategoriesas $category)
<div class="form-group">
<label class="control-label">{{$category->name}}</label>
<div class="row">
<input type="hidden" name="categoryname[]" value="{{$category->id}}">
@foreach($category->properties as $property)
<div class="col-md-2 mg-t-20 mg-lg-t-0">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="property{{$property->id}}" name="properties[]" value="{{$property->id}}">
<label class="custom-control-label" for="property{{$property->id}}">{{$property->name}}</label>
</div>
</div>
@endforeach
</div>
</div>
@endforeach
@endif
控制器端同步代码
$properties = $request->input('properties ');
$categories= $request->input('categories');
$car = Car::find($id);
$car->properties()->sync([$properties,$categories]);
我的数据透视表有 3 列,如下所示;
car_id car_property_id car_property_category_id
但我无法在此表中同步类别。只有 car_id 和 property_id 可以同步
我希望所有类别和属性必须同时同步。
不是:我用数组保存解决了这个问题
如果有人需要以下代码;
我想到了。如有需要;
$data = [];
foreach($request->properties as $property){
$add = [];
$find= CarProperty::where('id',$property)->first();
$add ['car_property_id'] = $find->id;
$add ['car_property_Category_id'] = $find->category->id;
$data[] = $add ;
}
$arac->properties()->sync($data );
解决方案
我想到了:
$data = [];
foreach($request->properties as $property) {
$add = [];
$find = CarProperty::where('id', $property)->first();
$add['car_property_id'] = $find->id;
$add['car_property_Category_id'] = $find->category->id;
$data[] = $add ;
}
$arac->properties()->sync($data);
推荐阅读
- amazon-web-services - 您可以使用 IAM 角色执行哪些您无法使用 IAM 组执行的操作?
- c# - 将回调传播到单独的线程
- arrays - 我不知道我的 AHK 脚本有什么问题
- gridview - 如何在 Yii2 Gridview 中通用更改 ActionColumn 图标?
- python - 如何将一个函数的输出写入文件?
- powerbi - PowerBI 为一种产品创建计算度量值,以与另一种产品的实际价值一起使用
- python - 在提交按钮 Crispy Form 上使用 HTML 元素和 {{user.userprofile.image.url}}
- selenium - 如何为两个不同的字符串创建使用包含方法的自定义 Xpath
- php - Wordpress:如何以编程方式创建帖子并在之前检查重复项
- cmake - 如果有的话,怎么可能检测到 CMakeLists.txt 是由“emcmake cmake”而不是“cmake”运行的?