Laravel and Eloquent: specifying columns when retrieving related items

This is the following message: Laravel 4 and Eloquent: getting all records and all related records

The resulting solution works fine:

$artists = Artist::with('instruments')->get(); return \View::make('artists')->withArtists($artists); 

It also works with simple:

 $artists = Artist::get(); 

Now I am trying to specify the exact columns to return for both tables. I tried using select() both the previous and my class, for example:

ArtistController.php

 $artists = Artist::select('firstname', 'lastname', 'instruments.name')->get(); 

or

 $artists = Artist::with(array('instruments' => function($query) { $query->select('name'); }))->get(); 

(as suggested here , and although this does not cause an error, it also does not limit the columns to only the specified ones)

or Artist.php :

 return $this->belongsToMany('App\Models\Instrument')->select(['name']); 

How can I get only the firstname and lastname from the artists table and the name column from the instruments table?

+3
source share
2 answers

Not sure what I was thinking. I think that working on this so long ago made me cross myself.

Anyway, I studied this a lot more and looked for answers and finally posted a question about GitHub.

The bottom line is not like in Laravel v4.1.

https://github.com/laravel/laravel/issues/2679

This solved it:

Artists.php

 public function instruments() { return $this->hasMany('App\Models\Instrument', 'id'); } 

Note that I changed this to hasMany with belongsToMany , which makes more sense to me, as musicians (or Artist ) will have a lot of Instrument that they play, and Instrument may belong to many Artist (which I also mentioned in previous questions, mentioned above). I also had to specify the 'id' column in my model, which tells ORM that instrument.id matches artist_instrument.id . This part confuses me a bit because I thought the order for hasMany was foreign_key , primary_key , but maybe I think about it back. If someone can explain this a bit more, I would appreciate it.

In any case, the second part of the decision ...

In ArtistsController.php, I did the following:

 $artists = Artist::with(array( 'instruments' => function($q) { $q->select('instruments.id', 'name'); }) )->get(array('id', 'firstname', 'lastname')); 

This gives me exactly what I want, this is a collection of artists that contains only the firstname and lastname from the artists table and the name column for each of the instruments that they play from instruments . Strike>

+3
source
 $artists = Artist::with(array('instruments' => function ($query) { $query->select('id', 'name'); }))->get('id', 'firstname', 'lastname'); 
+2
source

Source: https://habr.com/ru/post/971556/


All Articles