Laravel Недопустимый аргумент для foreach - PullRequest
0 голосов
/ 01 июля 2018

Модель Доктор

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 указан неверный аргумент ()

Я пытался установить связь между Доктором и Адресом, но это не работает. Если я попробую dd ($ doctor-> address), у меня будет ноль.

Ответы [ 2 ]

0 голосов
/ 01 июля 2018

имеет ли смысл, что у доктора много адресов, а у адреса много врачей? Исходя из ваших моделей, у вас есть много-много отношений между врачами и адресами?

Почему бы тебе не сделать это таким образом. у врача много адресов? отношения один ко многим

тогда ваши модели будут такими же.

Модель доктора

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
0 голосов
/ 01 июля 2018

Вы ссылаетесь на один и тот же класс в ваших отношениях («Доктор принадлежит доктору»), который, вероятно, не может работать.

Попытка:

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