Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在laravel中以一对多的关系正确显示来自两个foreach的数据?_Laravel_Eloquent - Fatal编程技术网

如何在laravel中以一对多的关系正确显示来自两个foreach的数据?

如何在laravel中以一对多的关系正确显示来自两个foreach的数据?,laravel,eloquent,Laravel,Eloquent,我试图显示一对多关系中的数据 型号: -车辆 public function VehicleClient(){ return $this->belongsto(VehicleClient::class,'vehicle_clients_id'); } Schema::create('vehicles', function (Blueprint $table) { $table->id();

我试图显示一对多关系中的数据

型号:

-车辆

public function VehicleClient(){
    
            return $this->belongsto(VehicleClient::class,'vehicle_clients_id');
        }


 
  Schema::create('vehicles', function (Blueprint $table) {
            $table->id();
            $table->string('color');
            $table->timestamps();
        });
-车辆客户

 public function Vehicle(){

        return $this->hasMany(Vehicle::class,'id');
    }
 Schema::create('vehicle_clients', function (Blueprint $table) {
            $table->id();
            $table->foreignId('vehicles_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
            $table->timestamps();
        });
迁移

-车辆

public function VehicleClient(){
    
            return $this->belongsto(VehicleClient::class,'vehicle_clients_id');
        }


 
  Schema::create('vehicles', function (Blueprint $table) {
            $table->id();
            $table->string('color');
            $table->timestamps();
        });
-车辆客户

 public function Vehicle(){

        return $this->hasMany(Vehicle::class,'id');
    }
 Schema::create('vehicle_clients', function (Blueprint $table) {
            $table->id();
            $table->foreignId('vehicles_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
            $table->timestamps();
        });
控制器

  public function show($id)
    {
     
        $Vehicle =  VehicleClient::where('clients_id',$id)->get();
       return view('clients.show', compact('Vehicles'));
    }
刀片:

  @foreach($Vehicles as $v)
    @foreach($v->Vehicle as $vehicle)
       <td>{{ $vehicle->nombres }}</td>
     @endforeach
 @endforeach
@foreach($v车辆)
@foreach($v->车辆作为$Vehicle)
{{$vehicle->nombres}
@endforeach
@endforeach
但在执行两个foreach时,将relationship属性添加到第二个foreach时遇到问题,该属性应用于中间表的id

这就是第一个foreach带来的:

身份证件 车辆识别号 1. 1. 3. 2. 5. 3.
显示数据库中的表或迁移文件我在这里看到一些错误。一对多关系没有中间表。关系颠倒了。在车辆模型中为车辆客户关系,在车辆客户模型中为车辆(复数形式,非车辆)功能。我认为您正在将车辆模型与自身联系起来。该查询正确地将表中的数据提取到数据库中。如果将
dd($vehicle->vehicle)放入数据库,您会得到什么在控制器中返回之前?此集合实例上不存在异常属性[Vehicle]。