0

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?

Ostet
  • 175
  • 1
  • 12
  • Try to include foreign key (it could be `author_id` or similar related to what is set in `Author` model as primary key). – Tpojka Dec 07 '22 at 14:44
  • Does this answer your question? [Get Specific Columns Using “With()” Function in Laravel Eloquent](https://stackoverflow.com/questions/19852927/get-specific-columns-using-with-function-in-laravel-eloquent) – Tpojka Dec 07 '22 at 14:45
  • Tpojka, unfortunately no. The author_id column is foreign key for id column of Author table. In recommended topic write same thing that I have already tried and it did not work out for me. This is strange. – Ostet Dec 07 '22 at 15:01

0 Answers0