user3253002
user3253002

Reputation: 1681

Laravel 5 eloquent: select specific column of relation

I have 2 models: Author and Post

In my Post model, I have an author function (One To Many (Inverse)):

public function author()
    {
        return $this->belongsTo('App\Author', 'author_id');
    }

Now I want to export to Excel the following information:

id | title | author name

This is what I tried:

$posts = Post::with(array(
        'author' => function ($query) {
            $query->select('name');
        }))->select('id', 'title')->get();

What I get is an empty author's name column.

What do I wrong?

Upvotes: 3

Views: 9385

Answers (2)

mul14
mul14

Reputation: 388

Since Laravel 5.5 you can use eager loading retrieve multiple specific columns simply by using string

Post::with('author:id,name')->get()

Author::with('posts:id,author_id,title')->get()

Notice the id or foreign key (author_id) must included, or data will be null.

Upvotes: 6

Alexander Kremenchuk
Alexander Kremenchuk

Reputation: 406

please try:

$posts = Post::with(['author' => function($query){
    $query->select(['id','name']);
}])->get(['id','title', 'author_foreign_key_in_posts_table']);

Having that, you'll be able to get:

$posts->first()->author->name;
$posts->first()->id;
$posts->first()->title;

You may use iteration or whatever instead of first() for export.

Upvotes: 5

Related Questions