Laravel为foreach提供了无效的参数

时间:2018-07-01 13:42:12

标签: php laravel voyager

模型医生

class Doctor extends Model
{
    public function addresses() {
        return $this->belongsTo(Doctor::class);
    }
}

型号地址

 class Address extends Model
    {
      public function doctors() {
          return $this->hasMany(Address::class);
      }
    }

DoctorsController

class DoctorsController extends Controller
{
    public function index()
    {
        $doctors = Doctor::with('addresses')->get();

        return view('doctors.index',compact('doctors'));
    }
}

刀片

@foreach($doctors as $doctor)
    {{ $doctor->name }}
    @foreach($doctor->addresses as $address)
        {{ $address->city }}
    @endforeach

@endforeach

我有一个错误

  

为foreach()提供的参数无效

我试图在Doctor和Address之间建立关系,但是这没有用。如果我尝试dd($ doctor-> addresses),则为空。

2 个答案:

答案 0 :(得分:0)

您在关系中引用了相同的类(“医生属于医生”),这可能无法正常工作。

尝试:

class Doctor extends Model
{
    public function addresses() {
        return $this->hasMany(Address::class);
    }
}
 class Address extends Model
    {
      public function doctors() {
          return $this->belongsTo(Doctor::class);
      }
    }

答案 1 :(得分:-1)

一个医生有很多地址而一个地址有很多医生有意义吗?根据您的模型,您确实在医生和地址之间存在多对多关系吗?

为什么不可以这样呢?医生有很多地址?一对多的关系

然后您的模型就是这种方式。

医生模型

class Doctor extends Model
{
    public function addresses() {
        return $this->hasMany('App\Address','DoctorId');// you need to indicate the foreign key if you didn't follow the laravel naming convention
    }
}

地址模型

class Address extends Model
{
    public function doctor() {
        return $this->hasOne('App\Doctor','DoctorId');// you need to indicate the foriegn key if you didn't follow the Laravel naming convention
      }
}

您控制

class DoctorsController extends Controller
{
    public function index()
    {
        $doctors = Doctor::all();//or Doctor::where('something','=','value')->get();

        return view('doctors.index',compact('doctors'));
    }
}

您的视图

@foreach($doctors as $doctor)
    {{ $doctor->name }}
    @foreach($doctor->addresses as $address)
        {{ $address->city }}
    @endforeach

@endforeach