M
M
miniven2016-04-19 12:40:41
HTML
miniven, 2016-04-19 12:40:41

How to write a database query in laravel?

I have a list of objects through foreach
Each object has several photos that are stored in another table.
I want each object to have the first photo of those related to it when the list of objects is displayed. How I am trying to do this:

@foreach ($objects->sortBy('id') as $object)
        <div class="row">
          <div class="col-md-8 object_admin panel">
            @if (count($photos) != 0)
              <div class="col-md-2 object_admin__image">
                <img src="{{ $photos->where('objects_model_id', $object->id)->first()->photo_path }}" alt="Фотография объекта">
              </div>
            @endif
            <div class="col-md-6">
              <span class="object_admin__price">Цена: {{ $object->object_price }}</span>
              <span class="object_admin__space">Площадь: {{ $object->object_space }}</span>
            </div>
            <div class="col-md-4 controls">
              <ul class="controls__list">
                <li class="controls__item"><a href="/object_{{ $object->id }}" class="btn btn-default">Редактировать</a></li>
                <li class="controls__item"><a href="/delete_obj_{{ $object->id }}" class="btn btn-default">Удалить</a></li>
              </ul>
            </div>

            @if (!empty($object->object_description))
              <div class="col-xs-12 object_admin__description">
                {{ $object->object_description }}
              </div>
            @endif
          </div>
        </div>
      @endforeach

How to do it right?
Here the moment is still such that if instead of $object-> id I substitute just a number, then everything works

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stanislav Pochepko, 2016-04-19
@DJZT

Make a connection between Photo and Objects models. One to many will be
Objects

public function photos(){
return $this->hasMany(Photo::class);
}

In general, read the Eloquent relationship documentation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question