Reputation: 21
I have two models, Event and CoverEvent. A cover event can only be linked to one event. I was able to do it using SQL. But I'd like to have it in a clean manner, using Eloquent. How should I do this?
Many thanks!
Here's the SQL:
SELECT
`cover_events`.`id`,
`events`.`slug`,
`events`.`title`,
`events`.`subtitle`,
`events`.`image`,
`cover_events`.`columns`,
`cover_events`.`right_align`,
`cover_events`.`dark_text`,
`cover_events`.`large`
FROM
`cover_events`,
`events`
WHERE
`is_visible` LIKE 'true' AND
`cover_events`.`event_id` = `events`.`id`
Which should result as the following array:
[
[
"id" => 1,
"slug" => 'celine-dion-2020',
"title" => 'Celine Dion',
"subtitle" => '31 July 2020',
"image" => env('APP_URL') . '/img/celine_dion.jpg',
"columns" => 8,
"right_align" => false,
"dark_text" => true,
"large" => true
],
...
]
Upvotes: 1
Views: 381
Reputation: 134
for example if your parent model is ManageClass and child modal is DaysClassDetails :-
class ManageClass extends Authenticatable
{
public function classType()
{
return $this->hasMany('App\DaysClassDetails','day_id','id');
}
}
and enter this command in your controller function
ManageClass::with('classType')->get();
Upvotes: 1
Reputation: 1814
In eloquent you can only use relationships to join tables..
In CoverEvent
class use a relationship
public function events()
{
return $this->hasOne('App\Models\Event', 'id', 'event_id');
}
Retrieve the result using
$res = CoverEvent::where('is_visible','true')->get();
foreach($res as $cover_event)
{
$cover_event->events->slug; // data from event class
$cover_event->columns; // data from cover_event class
}
Upvotes: 1
Reputation: 3537
You could use Laravel's collection merge() method:
$events = Event::all()->merge(CoverEvent::all());
Upvotes: 0