I need get specify columns of the relationship. But both recomended in documentation way don't work for me. I can do this by specifying the desired columns in the model, but I don't want to do it: maybe in the future I will need this relationship elsewhere with more (or fewer) columns.
Data base: table Author (id, name) and Article (id, title, author_id)
The author_id column is foreign key for id column of Author table.
Controller:
//it display all columns
$pack = Author::with(['Article' => function ($query) {
$query->select('id', 'title');
}])
->where('id', $id)
->get();
//also it display all columns
$pack = Author::query()
->with(['Article' => function ($query) {
$query->select('id', 'title');
}])
->where('id', $id)
->get()
//also it display all columns
$pack = Author::with(['Article:id,title'])
->where('id', $id)
->get();
Model:
class Author extends Model
{
protected $guarded = [];
public function Article()
{
return $this->hasMany('App\Models\Article')
//->select('id', 'title'); //If uncommented, then specifying columns works
;
}
}
Why doesn't specifying columns in the controller work for me?