Laravel 为 foreach 提供的参数无效

Laravel Invalid argument supplied for foreach

模范医生

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

模型地址

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

医生控制器

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

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

Blade

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

@endforeach

我有一个错误

Invalid argument supplied for foreach()

我试图在 Doctor 和 Address 之间建立关系,但它不起作用。如果我尝试 dd($doctor->addresses) 我有 null.

您在您的关系 ("Doctor belongs to Doctor") 中引用了相同的 class,这可能行不通。

尝试:

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

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

你为什么不可以这样做。一个医生有多个地址?一对多关系

那么你的模型就是这样的

博士模型

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