A
A
Andrey Surzhikov2016-11-24 15:31:07
ORM
Andrey Surzhikov, 2016-11-24 15:31:07

How to correctly select certain columns in Relations ORM?

I'm trying in Laravel5 to make the correct hasMany relationship with a selection of multiple columns from a child table.
There is an Event model (event) attached to it one or more Diploma (Diploma).
For the Event from the Diploma table, I only need to select some fields (id and name), because there are very large fields that do not need to be pulled every time.

Таблица events:
id
name
date

Таблица diplomas:
id
event_id
name
setupdata

I do this:
Model
<?php
namespace osportid\Models;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
  protected $table = 'events';
  /**
   *	Получить дипломы для Мероприятий
   */
  public function event_diplomas()
  {
    return($this->hasMany('osportid\Models\Diploma', 'event_id', 'id'));
  }
}

Controller:
In this option, everything works, but displays all the fields from the diplomas table at once
.....
  /*
    Show Event View by event Identify
  */
  public function getEvent($id)
  {	
    $event = Event::with(['event_diplomas'])->where("id", '=', $id)->firstOrFail();
    dd($event);
  }
.....

This does not work (event_diplomas output is empty)
<?php
namespace osportid\Models;
use Illuminate\Database\Eloquent\Model;
class Event extends Model
{
  protected $table = 'events';
  /**
   *	Получить дипломы для Мероприятий
   */
  public function event_diplomas()
  {
    return($this->hasMany('osportid\Models\Diploma', 'event_id', 'id')->select('id','name')));
  }
}

This doesn't work either (event_diplomas output is empty again)
.....
  /*
    Show Event View by event Identify
  */
  public function getEvent($id)
  {	
    $event = Event::with([
      'event_diplomas'=>function($query)
      {
        $query->select('id', 'name');
      }
    ])->where("id", '=', $id)->firstOrFail();
    dd($event);
  }
.....

I re-read a cloud of foreign forums and Stackoverflow, and found these solutions, but as I understood from the comments, they work for someone, they don’t work for someone.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Surzhikov, 2016-11-24
@Surzhikov

Found in the open spaces of Laracasts;
https://laracasts.com/discuss/channels/eloquent/el...
The idea is that the selection must contain a foreign index and a primary index.
So, I did it and it all worked.

.....
  /*
    Show Event View by event Identify
  */
  public function getEvent($id)
  {	
    $event = Event::with([
      'event_diplomas'=>function($query)
      {
        $query->select('id', 'event_id', 'name');
      }
    ])->where("id", '=', $id)->firstOrFail();
    dd($event);
  }
.....

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question