Answer the question
In order to leave comments, you need to log in
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
<?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'));
}
}
.....
/*
Show Event View by event Identify
*/
public function getEvent($id)
{
$event = Event::with(['event_diplomas'])->where("id", '=', $id)->firstOrFail();
dd($event);
}
.....
<?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')));
}
}
.....
/*
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);
}
.....
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question