0

模范医生

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'));
    }
}

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

@endforeach

我有一个错误

为 foreach() 提供的参数无效

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

4

2 回答 2

0

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

尝试:

class Doctor extends Model
{
    public function addresses() {
        return $this->hasMany(Address::class);
    }
}
 class Address extends Model
    {
      public function doctors() {
          return $this->belongsTo(Doctor::class);
      }
    }
于 2018-07-01T13:51:18.857 回答
-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
于 2018-07-01T14:01:55.543 回答