Reputation: 1781
I have two model (Event and Occurence) with db tables that are linked by a relationship:
*events:*
$table->id();
$table->unsignedBigInteger('institution_id');
$table->time('start_time', 0);
$table->time('end_time', 0);
$table->timestamps();
$table->softDeletes();
and
*event_occurence:*
$table->id();
$table->unsignedBigInteger('event_id');
$table->date('occurs_at');
$table->foreign('event_id')
->references('id')
->on('events');
Then
In Event class:
public function occurences()
{
return $this->hasMany(Occurence::class);
}
Now, I'm tring to get back the 'occurs_at' field in an array when I do an Eloquent call by using a scope. Here is the scope function:
public function scopeWithDates($query)
{
$query->with('occurences:occurs_at');
}
And here is my call:
$events = Event::withDates()->get();
return $events;
When I do this, my occurences object on the return is empty. But, when I do:
public function scopeWithDates($query)
{
$query->with('occurences:event_id');
}
I get the event IDs. Why? Can you only do ->with and select specific columns on foreign keys?
Upvotes: 0
Views: 46
Reputation: 1769
While getting specific record from laravel relationship, you have to specify the foreign key and then other fields.
$query->with('occurences:event_id,occurs_at');
And I haven't tested it in Scope but it may also work in this way
$query->with(['occurences' => function($record){
$record->select('event_id','occurs_at');
}]);
Upvotes: 0
Reputation: 181
You can select specific columns, but you always have to specify the foreign key.
Get Specific Columns Using “With()” Function in Laravel Eloquent
Upvotes: 1